反射
反射第一步 获取类class对象
Class c1 = Class.forName("全类名")
Class c2 = 类名.class
Class c3 =对象.getClass()
** 获取Constructor构造器对象 成员变量 方法 **
Class<?> student = Class.forName("Student");
Constructor<?> constructor = student.getDeclaredConstructor();
//打开权限 暴力反射
constructor.setAccessible(true);
** 创建对象 赋值 运行**
Student o = (Student) constructor.newInstance();
o.setAge(11);
o.setName("11");
System.out.println(o);
System.out.println(Student.getINSTANCE()==o);
反射突破泛型限制
List<Integer> list = new ArrayList<>();
Class<? extends List> listClass = list.getClass();
Method add = listClass.getDeclaredMethod("add", Object.class);
Object invoke = add.invoke(list,"get");
System.out.println(invoke);
System.out.println(list);
通过反射在泛型为Integer的集合添加String类型数据
注解
自定义注解 :@interface
元注解 :注解中注解
注解解析
** 自定义注解类**
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MBook {
String name();
//默认值 99
int price() default 99;
}
解析注解小demo
public class test {
@Test
public void test1(){
//解析方法上的注解
try {
//获取class对象
Class<?> bookStore = Class.forName("BookStore");
//获取方法
Method m = bookStore.getDeclaredMethod("mybook");
System.out.println(m.isAnnotationPresent(MBook.class));
//判断方法上是否有注解
if (m.isAnnotationPresent(MBook.class)) {
//获取注解
MBook declaredAnnotation = m.getDeclaredAnnotation(MBook.class);
System.out.println(declaredAnnotation.price());
System.out.println(declaredAnnotation.name());
}
} catch (ClassNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
}
class BookStore{
@MBook(name="雨天飞行",price = 199)
public void mybook() {
}
}