第十六章,

一.反射

1.使用枚举类型设置常量
每个Constructor对象代表一个构造方法,利用Constructor对象可以操纵相应的构造方法:

getConstructorss()
getConstructorss(Class<?>...parameterTypes)
getDeclaredConstructors()
getDeclaredConstructor(Class<?>...parameterTypes)

        2.访问成员变量
在通过下列一组方法访问成员变量时,将返回Field类型的对象或数组。每个Field对象代表一个成员变量,利用Field对象可以操纵相应的成员变量:

getFields()
getField(String name)
getDeclaredFields()
getDeclaredFields(String name)
如果是访问指定的成员变量,可以通过该成员变量的名称来访问。

        3.访问成员方法
在通过下列一组方法访问成员方法时,将返回Method类型的对象或数组。每个Method对象代表一个方法,利用Method对象可以操作对应的方法:

getMethods()
getMethods(String name,Class<?>...parameterTypes)
getDeclaredMethods()
getDeclaredMethods(String name,Class<?>...parameterTypes)
如果是访问指定的方法,需要根据该方法的名称和入口参数的类型来访问。 

二.Annotation注解功能 


        1.定义Annotation类型
在定义Annotation类型时,也需要用到用来定义接口的interface关键字,但需要在interface关键字前加一个“@”符号,即定义Annotation类型的关键字为@Annotation,这个关键字的隐含意思是继承了java.lang.annotation.Annotation接口。

public @Interface NoMemberAnnotation{
}
public @Interface NoMemberAnnotation{
    String value();
}
public @Interface NoMemberAnnotation{
    String describe();
    Class type();
}
public @Interface NoMemberAnnotation{
    String describe() default"<默认值>";
    Class type() default void.class;
}
 

        2.访问Annotation信息
如果在定义Annotation类型时将@Retention设置为RetentionPolicy.RUNTIME,那么在运行程序时通过反射就可以获取到相关的Annotation信息。
 

猜你喜欢

转载自blog.csdn.net/2302_76534913/article/details/134189209
今日推荐