1、反射
1.1、可以在程序运行时操作对象;解耦,提高可扩展性。
1.2、获取Class对象
- Class.forName(“类名”);xxx.class;xxx.getClass();
1.3、动态代理,Proxy也是用反射实现;
private void test() throws Exception {
Class<Person> cls1 = Person.class;
Field age = cls1.getDeclaredField("age");
age.setAccessible(true); // 暴力反射
Person person1 = new Person("张三", 18);
System.out.println(age.get(person1));
System.out.println("-----------------");
Constructor<Person> constructor = cls1.getConstructor(String.class, int.class);
Person person2 = constructor.newInstance("李四", 23);
System.out.println(person2);
}
6、注解
- 主要用于文档注释,编译检查、代码分析。
- 可以把注解理解为标签;它给解析程序使用。
@Deprecated
@SuppressWarnings("all") // 压制警告
- javap:反编译
C:\Users\Lumir>D:
D:\>cd Code
D:\Code>javac MyAnno.java
D:\Code>javap MyAnno.class
Compiled from "MyAnno.java"
public interface MyAnno extends java.lang.annotation.Annotation {
}
D:\Code>
- 元注解
/**
* ElementType.TYPE->只能作用在类上,
* @author Lumir
*
*/
@Target(value= {ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
/**
* RetentionPolicy.RUNTIME:该注解会保留到class文件中,并被jvm读取到
* CLASS:不能被jvm读取
* SOURCE:不会保留到class文件中
*
*/
@Retention(RetentionPolicy.SOURCE)
/**
* 标注了该注解的类中,该注解是否被抽取到doc文档中
*/
@Documented
/**
* 描述注解是否被子类继承
*/
@Inherited
public @interface MyAnno {
int age();
String name() default "张三";
}
- 反射获取注解属性值
// 自定义注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {
String className();
String methodName();
}
@Pro(className="grammar_test.reflect.Person", methodName="buyHouse")
public class Test2 {
public static void main(String[] args) {
Test2 t = new Test2();
t.test();
}
private void test() {
Class<Test2> cls = Test2.class;
Pro pro = cls.getAnnotation(Pro.class);
String className = pro.className();
String methodName = pro.methodName();
System.out.println(className);
System.out.println(methodName);
}
}