反射获取字节码Class对象的三种方式、反射_Class对象功能概述

反射获取字节码Class对象的三种方式

* *Field[] getFields() :获取所以public修饰的成员变量
* Field getField( string name):获取指定public的成员变量
* Field[] getDeclaredFields() :获取所以的成员变量
* Field getDeclaredField(string name) ;获取单个的
* setAccessible :暴力反射
public static void main(String[] args) throws Exception {
Class<Student> aClass = Student.class;


/**
* * *Field[] getFields()
* * Field getField( string name)
* * Field[] getDeclaredFields()
* * Field getDeclaredField(string name)
*/
Field[] fields = aClass.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("-------------");
Field a = aClass.getField("a");
Student student = new Student();
Object o = a.get(student);
System.out.println(o);
a.set(student, "大傻");
System.out.println(student);
System.out.println("------------------");
for (Field field : aClass.getDeclaredFields()) {
System.out.println(field);
}
System.out.println("-------------------");
Field d = aClass.getDeclaredField("d");
d.setAccessible(true); //暴力反射
Object o1 = d.get(student);
System.out.println(o1);
}

我们来看运行结果:

  

 

  

反射_Class对象功能概述

 

public class Test2 {
/**
* 获取构造方法们
* * 来constructor<? >[]getConstructors() :获取构造器
* * Constructor<T> getConstructor(类<?>... parameterTypes)
* * 末Cpnstructor<T> getDeclaredConstructor(类<?>. .. parameterTypes)*Constructor<?>[getDeclaredConstructors()
* * <p>
* @param args
*/
public static void main(String[] args) throws Exception {
Class<Student> aClass = Student.class;
Constructor<Student> constructor = aClass.getConstructor();
System.out.println(constructor);
Student student = constructor.newInstance(); //newInstance 创建对象
System.out.println(student);

}
}

 

posted @ 2022-07-27 09:31  一位程序袁  阅读(27)  评论(0编辑  收藏  举报