Class
-
属性
- 类名
- 修饰符
- 类的方法
- 类的属性
- 类的构造器
-
方法
-
创建一个该类的实例
-
在某个实例上调用该类的方法
-
//创建反射的三种方法:
Class<Dog> dogClass = Dog.class;
Class<?> dogClass2 = new Dog(12).getClass();
try {
Class<?> dogClass3 = Class.forName("com.chinasofti.se.misc.Dog");
} catch (ClassNotFoundException e) {
e.printStackTrace(); }
怎么取他们的 类名:dogClass.getSimpleName()或dogClass.getCanonicalName()
public class Test {
public static void main(String[] args) {
Class<? extends Dog> doglass = new Dog().getClass();
try {
Dog dog= doglass.newInstance();//操作反射,创建dog实例
/*
* dog.setAge(2); dog.setName("旺财");
*/
System.out.println(dog);
Field[] declaredFields = doglass.getDeclaredFields();
//取出的是属性(field)
Method[] declaredMethods = doglass.getDeclaredMethods();
//取出的是方法(method)通过invoke来反射方法
Constructor<?>[] declaredConstructors = doglass.getDeclaredConstructors();
//取出的是构造方法(constructor)
for (Field field : declaredFields) {
System.out.println(field+"取出所有的属性的类型"+field.getType());
}
Field ageField = doglass.getDeclaredField("age");
//取出里面的一个私有的属性,是int性
Field nameField = doglass.getDeclaredField("name");
Field otheraNameField = doglass.getDeclaredField("name");
ageField.setAccessible(true);//如果被注释掉,则不能操作private属性
//Dog dog2=new Dog();
int age = ageField.getInt(dog);
//getint里面的是创建的dog实例(dog和dog2是一样的意思),也就是new dog出来的实例
String name = nameField.getName();
otheraNameField.getType();
otheraNameField.getLong(name);//等等
otheraNameField.getModifiers();//去方法数量
System.out.println( "反射的属性,把private破坏掉 "+" "+" age的属性值为s"+age);
System.out.println( "反射的属性,把private破坏掉 "+" "+" age的属性值为s"+name);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}}
笔记提取:
Dog dog= doglass.newInstance();//操作反射,创建dog实例
Field[] declaredFields = doglass.getDeclaredFields();//取出的是属性(field)
Method[] declaredMethods = doglass.getDeclaredMethods();
//取出的是方法(method)通过invoke来反射方法
Constructor<?>[] declaredConstructors = doglass.getDeclaredConstructors();
//取出的是构造方法(constructor)
取出类里面的私有属性:
Field ageField = doglass.getDeclaredField("age");
Field nameField = doglass.getDeclaredField("name");
操作私有属性:
ageField.setAccessible(true);//如果被注释掉,则不能操作private属性
得到他们的属性的类型,值,方法个数等:
int age = ageField.getInt(dog);
//getint里面的是创建的dog实例(dog和dog2是一样的意思),也就是new dog出来的实例
otheraNameField.getType();