java反射和注解

反射

Class<?> aClass = Class.forName("reflect.Student");
Constructor<?> constructor = aClass.getConstructor();//构造函数,用于创建对象
Object obj = constructor.newInstance(); //创建对象,用于执行函数

Method[] methods = aClass.getMethods();//获取方法
for (Method method : methods) {
    System.out.println(method);
}
Method out = aClass.getMethod("out");//获取指定方法
out.invoke(obj);//执行方法

Field[] fields = aClass.getDeclaredFields();//获取所有属性(包括private)
for (Field field : fields) {
    System.out.println(field.getName());
}
fields[0].setAccessible(true); //给属性解锁  fields[0]  private name;
fields[0].set(obj, "小明"); //给属性赋值
System.out.println(obj);

//获取注解
Class<BookStore> bookStoreClass = BookStore.class;
Method buyBook = bookStoreClass.getMethod("buyBook");
//判断是否有注解,如果用buyBook则获取的是类上的注解
if (bookStoreClass.isAnnotationPresent(Book.class)) {
    Book annotation = bookStoreClass.getAnnotation(Book.class);
    //输出注解
    System.out.println(annotation.value());
    System.out.println(Arrays.toString(annotation.authors()));
}

注解

元属性

@Target
ElemenetType:
TYPE:用在类,接口上
FIELD:用在成员变量上
METHOD用在方法上
PARAMETER:用在参数上
CONSTRUCTOR:用在构造方法上
LOCAL_VARIABLE:用在局部变量上

@Retention
RetentionPolicy:
SOURCE:注解只存在于Java源代码中,编译生成的字节码文件中就不存在了。
CLASS:注解存在于Java源代码、编译以后的字节码文件中,运行的时候内存中没有,默认值。
RUNTIME:注解存在于Java源代码中、编译以后的字节码文件中、运行时内存中,程序可以通过反射获取该注解。

自定义注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Book {
    //  当注解中只有一个属性且名称是value,在使用注解时给value属性赋值可以直接给属性值

    //书名
    String value();

    //价格
    double price() default 100;

    //作者
    String[] authors();
}

使用案例

@Book(value = "红楼梦",authors = "曹雪芹",price = 998)
public class BookStore {

    @Book(value = "西游记",authors = {"吴承恩"})
    public void buyBook(){

    }
}

原文地址:https://www.cnblogs.com/birdofparadise/p/9769293.html