java-反射

image

image

image

创建对象,设置属性

public class MyTest {
	@Test
	void name() throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
		Class<?> aClass = Class.forName("cn.tjhis.domain.Dept");
		// 创建对象
		Object obj = aClass.getDeclaredConstructor().newInstance();
		// 反射字段
		Field deptno = aClass.getDeclaredField("deptno");
		Field deptName = aClass.getDeclaredField("dname");
		// 由于字段私有,设置访问权限
		deptno.setAccessible(true);
		deptName.setAccessible(true);
		// 设置值
		deptno.set(obj,1);
		deptName.set(obj,"总经理办公室");
		System.out.println(obj);
		// 获取类上的注解
		TableName declaredAnnotation = aClass.getDeclaredAnnotation(TableName.class);
		String value = declaredAnnotation.value();
		
		// 获取方法
		Method getDeptno = aClass.getDeclaredMethod("getDeptno");
		// 执行方法
		Object invoke = getDeptno.invoke(obj);

		System.out.println("invoke = " + invoke);
	}
}
posted @ 2023-02-27 17:07  his365  阅读(10)  评论(0编辑  收藏  举报