在JDK中,主要由以下类来实现Java反射机制
Class类:代表一个类。
Field 类:代表类的成员变量(成员变量也称为类的属性)。
Method类:代表类的方法。
Modifier类:代表修饰符。
lConstructor 类:代表类的构造方法。
Array类:提供了动态创建数组,以及访问数组的元素的静态方法。
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public class Demo2 {
public static void main(String[] args) {
Student stu=new Student();
Class clzStu= stu.getClass();
//fields 拿到属性
Field[] fields = clzStu.getDeclaredFields();
System.out.println("fields"+Arrays.toString(fields));
try {
Field name = clzStu.getDeclaredField("name");
System.out.println(name);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
//method 得到方法
System.out.println("-------------------------");
Method[] methods = clzStu.getDeclaredMethods();
System.out.println(Arrays.toString(methods));
try {
Method ff = clzStu.getDeclaredMethod("ff", String.class);
System.out.println(ff);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Method[] methods1 = clzStu.getMethods();
System.out.println(Arrays.toString(methods1));
//Modifiers 访问修饰符
System.out.println("--------------------------");
int modifiers = clzStu.getModifiers();
System.out.println(modifiers);
//Constructor 构造函数
Constructor[] constructors = clzStu.getConstructors();
System.out.println(Arrays.toString(constructors));
try {
Constructor anInt = clzStu.getConstructor();
System.out.println(anInt);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
Constructor constructor = null;
try {
constructor = clzStu.getConstructor(int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println(constructor);
}
}
public class Student {
private String name;
private int glod;
public Student(String name){
this.name=name;
}
public Student(int glod){
this.glod=glod;
}
private Student(String name,int glod){
this.name=name;
this.glod=glod;
}
@Override
public String toString() {
return "name:"+name+",glod:"+glod;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGlod() {
return glod;
}
public void setGlod(int glod) {
this.glod = glod;
}
public Student(){
}
public void ff(String xx){
}
}
技术总结:
只要你不跪着这个世界没人比你高 ! ! !
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步