目录
反射可以获取构造函数,创建类对象
Class<User> clazz = (Class<User>) Class.forName( "reflection.User");
//通过反射API调用构造方法,构造对象
User user = clazz.newInstance();//其实调用的是User的无参构造方法
Constructor<User> constructor = clazz.getDeclaredConstructor(int.class, String.class, int.class);
User user2= constructor.newInstance(1, "张三", 30);
System.out.println(user2.getName());
反射可以获取类中的方法,并调用
//通过反射API调用普通方法
User user3 = clazz.newInstance();
Method m01 = clazz.getDeclaredMethod("setName", String.class);
m01.invoke(user3, "李四");
System.out.println(user3.getName());
反射可以操作私有属性
//通过反射API操作私有属性
User user4 = clazz.newInstance();
Field field = clazz.getDeclaredField("name");
//开启和禁用访问安全检查的开关,值为true,则指示反射的对象在使用时应该取消Java语言访问检查。值为false,则指示反射的对象应该实施Java访问检查
field.setAccessible(true);
field.set(user4, "Du");//直接通过反射机制写属性
System.out.println(user4.getName());
反射可以获取指定方法参数泛型信息
//获取指定方法参数泛型信息
Method m2 = TestDemo01.class.getMethod("test01", Map.class, List.class);
Type[] types=m2.getGenericParameterTypes();
for(Type type : types) {
System.out.println("#"+type);
if(type instanceof ParameterizedType) {
Type[] genericTypes = ((ParameterizedType)type).getActualTypeArguments();
for(Type genericType : genericTypes) {
System.out.println("泛型类型: "+genericType);
}
}
}
反射可以获取指定方法返回值泛型信息
//获取指定方法返回值泛型信息
Method m03= TestDemo01.class.getMethod("test02", null);
Type returnType= m03.getGenericReturnType();
if(returnType instanceof ParameterizedType) {
System.out.println("@"+ returnType);
Type[] types2= ((ParameterizedType)returnType).getActualTypeArguments();
for(Type type:types2) {
System.out.println("返回值的泛型类型: "+type);
}
}
反射可以操作注解
String path = "annotation.Students";
try {
Class clazz = Class.forName(path);
Annotation[] allAnnotation=clazz.getAnnotations();
for(Annotation a:allAnnotation) {
System.out.println(a.annotationType());
}
//通过反射获取类的指定注解内容
Table table_annotation = (Table) clazz.getAnnotation(Table.class);
System.out.println(table_annotation.value());
//通过反射获取类的所有带注解的字段
Field[] fields = clazz.getDeclaredFields();
for(Field f: fields) {
if(f.isAnnotationPresent(annotation.Field.class)) {
annotation.Field subField =f.getAnnotation(annotation.Field.class);
System.out.println("column Name " + subField.columnName());
System.out.println(" type " + subField.type());
System.out.println(" length " + subField.lenght());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}