package com.etime.ssm;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) {
//方法一
Student student=new Student();
Class<? extends Student> class1 = student.getClass();
//方法二
Class<Student> class2 = Student.class;
//方法三
try {
Class<?> class3 = Class.forName("com.etime.ssm.Student");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//获取对象
Student student1=null;
Student student2=null;
try {
//方法一:class对象直接newinstance
student1 = class1.newInstance();
//方法二:通过构造器,再newinstance
Constructor<? extends Student> constructor = class1.getConstructor();
student2 = constructor.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//获取method对象
try {
Method getName = class1.getMethod("setName", String.class);
getName.invoke(student2,"wangwu");
System.out.println("学生2的名字"+student2.getName());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
//获取field对象
try {
//获取私有的属性使用declared方法
Field field=class1.getDeclaredField("age");
//安全性检查设置为true
field.setAccessible(true);
//给属性名赋值
field.set(student1, "18");
//获取属性名的值
Method setAddress = class1.getMethod("setAddress", String.class);
setAddress.invoke(student2, "成都");
Method getAddress = class1.getMethod("getAddress");
Object addr = getAddress.invoke(student2);
System.out.println("学生二的地址"+addr);
System.out.println(field.get(student1));
} catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
String getAddress="getAddress";
String setAddress="setAddress";
try {
Method method = class1.getMethod(setAddress, String.class);
method.invoke(student1, "昆明");
System.out.println("学生一的地址"+student1.getAddress());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
Java反射示例运用
最新推荐文章于 2024-07-30 20:50:32 发布