@liruiyi962464
2018-08-14T04:01:37.000000Z
字数 2305
阅读 510
java
- 反射可以通过源代码文件获得类的所有信息
- 反射可以通过字节码文件获得类的所有信息
- 以前通过类来获得对象,现在可以通过字节码获得对象
//已知一个类名,使用类名.class属性来获得字节码文件
Class c1 = People.class;
//已知字节码文件的完整路径,使用Class.forName("路径")路径出错时会抛出异常
try {
Class c2 = Class.forName("com.fanshe.fanshe");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//已知一个对象,使用对象名.getClass()来获得该类型的字节码对象
Student s1 = new Student();
Class c3 = s1.getClass();
//无参的
People p1 = (People) c1.newInstance();
p1.name = "战三";
System.out.println(p1.name);
People p2 = (People) c1.getConstructor(new Class[]{})
.newInstance(new Object[]{});
System.out.println(p2);
//有参的
People p3 = (People) c1.getConstructor(new Class[]{String.class,int.class,char.class}).
newInstance("李四",12,'男');
System.out.println(p3.name);
/*
* 使用反射 去操作属性
* getDeclaredField() 获得当前类型的指定的属性(包括私有的)
* getField() 获得当前类型和父类中指定的公有的属性
*
* getDeclaredFields() 获得当前类型的所有的属性(包括私有的)
* getFields() 获得当前类型和父类中所有的公有的属性
* */
Field[] fields = Student.class.getDeclaredFields();
for (Field f : fields) {
System.out.println(f.getName());
}
//获得指定的属性
Field field = Student.class.getDeclaredField("teacherId");
System.out.println(field.getName());
Student stu1 = new Student();
s1.setTeacherId(100);
//允许使用私有的属性
field.setAccessible(true);
//修改指定对象的属性值
field.set(stu1, 900);
//获取指定对象的属性值
System.out.println(field.get(stu1));
/*
* 使用反射获得和调用方法
* getDeclaredMethod() 获得当前类型的指定的方法(包括私有的)
* getMethod() 获得当前类型和父类中指定的公有的方法
*
* getDeclaredMethods() 获得当前类型的所有的方法(包括私有的)
* getMethods() 获得当前类型和父类中所有的公有的方法
* */
//获得指定的方法
Method method = Student.class
.getDeclaredMethod("study",new Class[]{String.class});
//允许使用方法
method.setAccessible(true);
//使用方法
method.invoke(stu1, new Object[]{"语文"});//si.study("语文")
/*
* 操作构造方法
* */
Class c5 = C.class;
//获得指定的构造方法
Constructor constructor = c5.getDeclaredConstructor(new Class[]{});
System.out.println(constructor.getName());
//允许使用私有的构造方法
constructor.setAccessible(true);
//使用构造方法创建对象
C c6 = (C) constructor.newInstance(new Object[]{});
c6.a();
class People{
public String name;
int age;
private char sex;
public People() {}
public People(String name, int age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void eat(String food){
System.out.println("吃"+food);
}
//此处省略get()、set()方法
}
class Student extends People{
public String schoolName;
String classroom;
private int teacherId;
public void study(String type){
System.out.println("学习"+type);
}
//此处省略get()、set()方法
}
class C{
private C(){}
public void a(){
System.out.println("C中的a方法");
}