public class TestReflect {
@Test
public void testClass() {
// 1 new
// Student stu = new Student();
// 2 forName
/*try {
Class.forName("com.reflect.demo.test.Student").newInstance();
} catch (Exception e) {
e.printStackTrace();
}*/
// 获取Student类的类对象
Class<?> clazz = Student.class;
Student stu = null;
try {
Constructor<?> cst = clazz.getDeclaredConstructor();
cst.setAccessible(true);
stu = (Student) cst.newInstance();
System.out.println(cst.newInstance());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 字段
Field[] fields = clazz.getDeclaredFields();
//Field[] fields = clazz.getFields(); // 获取public修饰的属性
for (Field field : fields) {
System.out.println(field);
}
System.out.println("--------------------------------------");
// 方法
// Method[] methods = clazz.getMethods(); // 获取当前类中中所有公有的方法
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
}
// 调用方法
try {
// 设置
Method method = clazz.getDeclaredMethod("setStuName",String.class);
method.invoke(stu, "张三");
// 获取
Method method1 = clazz.getDeclaredMethod("getStuName");
String name = (String) method1.invoke(stu);
System.out.println(name);
// 获取对应字段
Field nameField = clazz.getDeclaredField("stuName");
nameField.setAccessible(true);
name = (String) nameField.get(stu);
System.out.println(name);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
反射
最新推荐文章于 2024-04-02 21:18:56 发布