- student类
public class Student {
private String name ;
private int age ;
public void say(String str){
System.out.println("say方法"+str);
}
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
java如何获取反射的对象
reflection:
public class reflection01 {
public static void main(String[] args) throws ClassNotFoundException {
//1.类名.class获取反射对象
Class<Student> class1 = Student.class;
//2.化对象.getClass().获取反射对象
/*Student student = new Student();
Class<? extends Student> class2 = student.getClass();*/
Class<? extends Student> class2 = new Student().getClass();
//3.Class.fotName("完整路径名")获取反射对象
Class<?> class3 = Class.forName("/AAD/src/com/qf/reflection/Student.java");
}
}
java反射改变实体类中属性值
public class reflection02 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Student student = new Student("大白", 18);
//第一次输出student
System.out.println(student);
//获取反射对象
Class<Student> class1 = Student.class;
//分别获取实体类私有属性的对象
Field name = class1.getDeclaredField("name");
Field age = class1.getDeclaredField("age");
//分别打开实体类私有属性的访问权限
name.setAccessible(true);
age.setAccessible(true);
//通过对应的属性对象 调用set方法,传递参数1:对象,参数2:属性值
name.set(student, "小白");
age.set(student, 56);
//第二次输出student
System.out.println(student);
}
}
java反射获取实体类中普通方法
public class reflection03 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//实例化对象
Student student = new Student();
//获取反射对象
Class<Student> class1 = Student.class;
//得到声明方法--获取student的say方法--参数1:方法名,参数2:形参类型的反射对象
Method method = class1.getDeclaredMethod("say", String.class);
//设置访问权限---true为打开访问权限
method.setAccessible(true);
//调用方法,传递对象和形参
method.invoke(student, "很开心!");
}
}
java-反射获取实体类的构造方法
public class reflection04 {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//获取反射对象
Class<? extends Student> class1 = new Student().getClass();
//获取构造方法--传递形参类型的反射对象
Constructor<? extends Student> constructor = class1.getDeclaredConstructor(String.class,int.class);
//打开访问权限
constructor.setAccessible(true);
//使用构造方法对象进行对象的实例化
Student student = constructor.newInstance("小白兔",66);
System.out.println(student);
}
}