反射与注解

反射


1、反射

在程序运行时,可以根据给定的类动态的获取类的信息

通过反射方式使用此类 SUN设计的反射相关组件放在:java.lang.reflect包

获取探测器对象(Class类型的对象):

// 方法一
User user = new User();
Class<?> c =  user.getClass();
获取父类
c.getSuperclass();

// 方法二
Class<?> c2 = User.class;

// 方法三(常用)
Class<?> c3 =	Class.forName(className); className:类的全路径

// 对基本数据类型的包装类
Class<?> c4 = Integer.TYPE;
int.class == Integer.TYPE

2、类加载器(ClassLoader)

// 1、系统类加载器#AppClassLoader
ClassLoader loader1 = ClassLoader.getSystemClassLoader();

// 2、扩展类加载器#ExtClassLoader
ClassLoader loader2 = loader1.getParent();  

// 3、引导类加载器#BootstrapClassLoader
ClassLoader loader3 = loader2.getParent();  //null

类加载器应用:通过类加载器获取项目资源

ClassLoader loader = ClassLoader.getSystemClassLoader();
InputStream in = loader.getResourceAsStream("db.properties");
//对properties文件,SUN设计了一个类:Properties类,直接解析此文件;
Properties prop = new Properties();
prop.load(in);
		
//获取文件信息
String user = prop.getProperty("user");
String password = prop.getProperty("password");
System.out.println("user ->" + user);
System.out.println("password ->" + password);
ClassLoader loader = ClassLoader.getSystemClassLoader();
//得到文件全路径
URL url =  loader.getResource("db.properties"); 

作用:加载Class文件

  • .class文件被类加载器加载并初始化后,会生成一个Class,然后进行实例化(如下图)

类加载器详细

  • AppClassLoader:系统类(应用程序)加载器,继承扩展类加载器,ClassLoader loader1 = ClassLoader.getSystemClassLoader(); 加载的是一个项目中classpath下的类。
  • ExtClassLoader:扩展类加载器,继承引导类加载器,
    ClassLoader loader2 = loader1.getParent(); 加载的是安装的jdk目录下jre\lib目录下的ext文件夹中的文件。
  • BootstrapClassLoader:即上方输出中的null,引导类加载器,该加载器存在但找不到,ClassLoader loader3 = loader2.getParent();加载的是安装的jdk目录下jre目录下lib文件夹中的rt.jar及一些其他的重要的文件。

父委托机制:类加载器加载Class文件时,会进行向上委托请求,即会先从系统类加载器委托扩展类加载器委托引导类加载器检查,然后引导类加载器检查是否存在这个类,存在则加载,不存在则抛出异常并委托子类加载。

关于引导类加载器为null:Bootstrap ClassLoader是由C/C++编写的,它本身是虚拟机的一部分,所以它并不是一个JAVA类,也就是无法在java代码中获取它的引用,JVM启动时通过Bootstrap类加载器加载rt.jar等核心jar包中的class文件,int.class,String.class都是由它加载。JVM初始化sun.misc.Launcher(java程序入口)并创建Extension ClassLoader和AppClassLoader实例,并将ExtClassLoader设置为AppClassLoader的父加载器,Bootstrap没有父加载器。

3、获取类信息

类的私有属性和方法是不能获取和执行的,但通过反射的方式可以获取与执行。

创建一个类Test:

public class Test {
    private String name;
    private int age;
    private int testint;

    public Test(){

    }
    public Test(String name){
        this.name = name;
    }
    public Test(String name, int age){
        this.name = name;
        this.age = age;
    }
    private Test(int age){
        this.age = age;
    }
    public Test(String name, int age, int testint){
        this.name = name;
        this.age = age;
        this.testint = testint;
    }
    //省略get、set方法
    @Override
    public String toString() {
        return "Test{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", testint=" + testint +
                '}';
    }
    
    private void welcome(String tip){
        System.out.println(tip);
    }
    public void hello(){
        System.out.println("hello,world");
    }
}
1、获取属性
  • getDeclaredFields():获取全部属性
  • getDeclaredField(“属性名”):获取指定属性
  • getType():获取属性类型
  • getName():获取属性名
  • getModifiers():获取构造方法的类型,返回值为int
  • Modifier.toString(int):获取构造方法的类型,将int转为String
Test test = new Test("zhangsan", 22, 1);
Class c = test.getClass();
Field[] fields = c.getDeclaredFields();
for(Field field : fields){
      System.out.println(Modifier.toString(field.getModifiers()) + " " + field.getType() + " " +  field.getName());
}
2、获取构造方法

1.获取全部构造方法

  • getDeclaredConstructors():获取全部构造方法
  • getConstructors():获取public类型的构造方法
  • getParameterTypes():获取构造方法的参数,返回值为Class数组
public class Demo1 {
    public static void main(String[] args) {
        Test test = new Test();
        Class c = test.getClass();
        Constructor[] constructors = c.getDeclaredConstructors();
        for(Constructor constructor : constructors){
            System.out.print(Modifier.toString(constructor.getModifiers()) + ":");
            Class[] parametertypes = constructor.getParameterTypes();
            for (int i = 0; i < parametertypes.length; i++) {
                System.out.print(parametertypes[i].getName() + " ");
            }
            System.out.println();
        }
    }
}
------------------------------------------------------------------------------------
public:java.lang.String int int 
private:int 
public:java.lang.String int 
public:java.lang.String 
public:

2.获取特定构造方法

获取无参构造方法:

  • getDeclaredConstructor():获取不带参数的构造方法
Test test = new Test();
Class c = test.getClass();
try {
	Constructor constructor = c.getDeclaredConstructor();
	System.out.println(constructor);
} catch (NoSuchMethodException e) {
	e.printStackTrace();
}
------------------------------------------------------------
public Test()

获取带参构造方法:

  • getDeclaredConstructor(Class[]):获取带参数的构造方法
Test test = new Test();
Class c = test.getClass();
//获取带String与int的构造方法
Class[] p = {String.class, int.class};
try {
	Constructor constructor = c.getDeclaredConstructor(p);
	System.out.println(constructor);
} catch (NoSuchMethodException e) {
	e.printStackTrace();
}
------------------------------------------------------------
public Test(java.lang.String,int)
3、获取普通方法
  • getDeclaredMethod(“方法名”, 类型.class):获取类的指定方法
  • getDeclaredMethods():获取全部方法
  • getMethods():获取父类和本类的全部方法
Test test = new Test();
Class c = test.getClass();
try {
    Method method = c.getDeclaredMethod("welcome", String.class);
    Method[] methods = c.getDeclaredMethods();
    for(Method method1 : methods){
        System.out.println(method1);
    }
    System.out.println(method);
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

4、反射应用

1、创建对象

调用构造方法:

  • newInstance(Object… initargs):通过带参构造方法创建对象
  • 调用私有构造方法需在调用前加上:constructor.setAccessible(true);
Class c = Test.class;
Class[] p = {String.class, int.class, int.class};
try {
	Constructor constructor = c.getDeclaredConstructor(p);
	constructor.setAccessible(true);
	Test test = (Test) constructor.newInstance("zhangsan", 22, 2);
	System.out.println(test);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | 		InvocationTargetException e) {
	e.printStackTrace();
}
------------------------------------------------------------
Test{name='zhangsan', age=22, testint=2}
2、设置属性
Test test = new Test("zhangsan", 22, 1);
Class c = test.getClass();
try {
	Field field = c.getDeclaredField("name");
	field.setAccessible(true);
	field.set(test, "lisi");
	System.out.println(test);
} catch (NoSuchFieldException | IllegalAccessException e) {
	e.printStackTrace();
}
3、调用方法
Class c = Test.class;
try {
    Class[] p = {String.class, int.class, int.class};
    Constructor constructor = c.getDeclaredConstructor(p);
    Test test = (Test) constructor.newInstance("zhangsan", 22, 1);
    //调用welcome方法
    Class[] p1 = {String.class};
    Method method1 = c.getDeclaredMethod("welcome", String.class);
    method1.setAccessible(true);
    Object[] val = {"hello, zhangsan"};
    method1.invoke(test, val);
    //调用hello方法
    Method method2 = c.getDeclaredMethod("hello");
    method2.invoke(test);
} catch (Exception e) {
    e.printStackTrace();
}

5、注解方法

//返回指定的注解
getAnnotation(注解.class)
//判断当前元素是否被指定注解修饰
isAnnotationPresent(注解.class)
//返回所有的注解
getAnnotations()

注解


1、注解简介

Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。

Java 语言中的类、方法、变量、参数和包等都可以被标注。和 Javadoc 不同,Java 标注可以通过反射获取标注内容。在编译器生成类文件时,标注可以被嵌入到字节码中。Java 虚拟机可以保留标注内容,在运行时可以获取到标注内容 ,也支持自定义 Java 标注。

2、三大内置注解

这三个注解放在java.lang中

  • @SuppressWarnings :指示编译器去忽略注解中声明的警告。 (unused:没有使用;unchecked:不检查语法;deprecation:过时的)

  • @Override :检查该方法是否是重写方法。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。

  • @Deprecated :标记过时方法。如果使用该方法,会报编译警告。

3、四大元注解

这四个注解放在 java.lang.annotation中

元注解:注解的注解 (作用在其他注解的注解)

  • @Target :标记这个注解应该是哪种 Java 成员。

  • @Documented :标记这些注解是否包含在用户文档中。

  • @Inherited :标记这个注解是继承于哪个注解类(默认注解并没有继承于任何子类) 。

  • @Retention :标识这个注解怎么保存,是只在代码中,还是编入class文件中,或者是在运行时可以通过反射访问。

java7之后,额外增加3个注解:

  • @SafeVarargs - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
  • @FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。
  • @Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。

4、注解架构

1、架构

注解架构

由上图左半部分可以看出:

(1)1 个 Annotation 和 1 个 RetentionPolicy 关联。

(2)1 个 Annotation 和 1~n 个 ElementType 关联。

(3)Annotation 有许多实现类,包括:Deprecated, Documented, Inherited, Override 等等。

java Annotation 的组成中,有 3 个非常重要的主干类 :AnnotationElementTypeRetentionPolicy

package java.lang.annotation;
public interface Annotation {

    boolean equals(Object obj);

    int hashCode();

    String toString();

    Class<? extends Annotation> annotationType();
}
package java.lang.annotation;

public enum ElementType {
    TYPE,               /* 类、接口(包括注释类型)或枚举声明  */

    FIELD,              /* 字段声明(包括枚举常量)  */

    METHOD,             /* 方法声明  */

    PARAMETER,          /* 参数声明  */

    CONSTRUCTOR,        /* 构造方法声明  */

    LOCAL_VARIABLE,     /* 局部变量声明  */

    ANNOTATION_TYPE,    /* 注释类型声明  */

    PACKAGE             /* 包声明  */
}
package java.lang.annotation;
public enum RetentionPolicy {
    SOURCE,            /* Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了  */

    CLASS,             /* 编译器将Annotation存储于类对应的.class文件中。默认行为  */

    RUNTIME            /* 编译器将Annotation存储于class文件中,并且可由JVM读入 */
}

说明:

(01) Annotation 就是个接口。

“每 1 个 Annotation” 都与 “1 个 RetentionPolicy” 关联,并且与 “1~n 个 ElementType” 关联。可以通俗的理解为:每 1 个 Annotation 对象,都会有唯一的 RetentionPolicy 属性;至于 ElementType 属性,则有 1~n 个。

(02) ElementType 是 Enum 枚举类型,它用来指定 Annotation 的类型。

“每 1 个 Annotation” 都与 “1~n 个 ElementType” 关联。当 Annotation 与某个 ElementType 关联时,就意味着:Annotation有了某种用途。例如,若一个 Annotation 对象是 METHOD 类型,则该 Annotation 只能用来修饰方法。

(03) RetentionPolicy 是 Enum 枚举类型,它用来指定 Annotation 的策略。通俗点说,就是不同 RetentionPolicy 类型的 Annotation 的作用域不同。

“每 1 个 Annotation” 都与 “1 个 RetentionPolicy” 关联。

  • a) 若 Annotation 的类型为 SOURCE,则意味着:Annotation 仅存在于编译器处理期间,编译器处理完之后,该 Annotation 就没用了。 例如," @Override" 标志就是一个 Annotation。当它修饰一个方法的时候,就意味着该方法覆盖父类的方法;并且在编译期间会进行语法检查!编译器处理完后,“@Override” 就没有任何作用了。
  • b) 若 Annotation 的类型为 CLASS,则意味着:编译器将 Annotation 存储于类对应的 .class 文件中,它是 Annotation 的默认行为。
  • c) 若 Annotation 的类型为 RUNTIME,则意味着:编译器将 Annotation 存储于 class 文件中,并且可由JVM读入。
2、Annotation通用定义
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation1 {
}

说明:

上面的作用是定义一个 Annotation,它的名字是 MyAnnotation1。定义了 MyAnnotation1 之后,我们可以在代码中通过 “@MyAnnotation1” 来使用它。 其它的,@Documented, @Target, @Retention, @interface 都是来修饰 MyAnnotation1 的。含义如下:

(01) @interface

使用 @interface 定义注解时,意味着它实现了 java.lang.annotation.Annotation 接口,即该注解就是一个Annotation。

定义 Annotation 时,@interface 是必须的。

注意:它和我们通常的 implemented 实现接口的方法不同。Annotation 接口的实现细节都由编译器完成。通过 @interface 定义注解后,该注解不能继承其他的注解或接口。

(02) @Documented

类和方法的 Annotation 在缺省情况下是不出现在 javadoc 中的。如果使用 @Documented 修饰该 Annotation,则表示它可以出现在 javadoc 中。

定义 Annotation 时,@Documented 可有可无;若没有定义,则 Annotation 不会出现在 javadoc 中。

(03) @Target(ElementType.TYPE)

前面我们说过,ElementType 是 Annotation 的类型属性。而 @Target 的作用,就是来指定 Annotation 的类型属性。

@Target(ElementType.TYPE) 的意思就是指定该 Annotation 的类型是 ElementType.TYPE。这就意味着,MyAnnotation1 是来修饰"类、接口(包括注释类型)或枚举声明"的注解。

定义 Annotation 时,@Target 可有可无。若有 @Target,则该 Annotation 只能用于它所指定的地方;若没有 @Target,则该 Annotation 可以用于任何地方。

(04) @Retention(RetentionPolicy.RUNTIME)

RetentionPolicy 是 Annotation 的策略属性,而 @Retention 的作用,就是指定 Annotation 的策略属性。

@Retention(RetentionPolicy.RUNTIME) 的意思就是指定该 Annotation 的策略是 RetentionPolicy.RUNTIME。这就意味着,编译器会将该 Annotation 信息保留在 .class 文件中,并且能被虚拟机读取。

定义 Annotation 时,@Retention 可有可无。若没有 @Retention,则默认是 RetentionPolicy.CLASS。

3、常用 Annotation

即架构图右半部分

@Deprecated  -- @Deprecated 所标注内容,不再被建议使用。
@Override    -- @Override 只能标注方法,表示该方法覆盖父类中的方法。
@Documented  -- @Documented 所标注内容,可以出现在javadoc中。
@Inherited   -- @Inherited只能被用来标注“Annotation类型”,它所标注的Annotation具有继承性。
@Retention   -- @Retention只能被用来标注“Annotation类型”,而且它被用来指定AnnotationRetentionPolicy属性。
@Target      -- @Target只能被用来标注“Annotation类型”,而且它被用来指定AnnotationElementType属性。
@SuppressWarnings -- @SuppressWarnings 所标注内容产生的警告,编译器将不再提醒这些警告

由于 “@Deprecated 和 @Override” 类似,“@Documented, @Inherited, @Retention, @Target” 类似;所以,仅对 @Deprecated, @Inherited, @SuppressWarnings 这 3 个 Annotation 进行说明。

1.@Deprecated

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Deprecated {
}

说明:

  • @interface – 用来修饰 Deprecated,意味着 Deprecated 实现了 java.lang.annotation.Annotation 接口;即 Deprecated 就是一个注解。
  • @Documented – 它的作用是说明该注解能出现在 javadoc 中。
  • @Retention(RetentionPolicy.RUNTIME) – 它的作用是指定 Deprecated 的策略是 RetentionPolicy.RUNTIME。这就意味着,编译器会将Deprecated 的信息保留在 .class 文件中,并且能被虚拟机读取。
  • @Deprecated 所标注内容,不再被建议使用。

2.@Inherited

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}

说明:

  • @interface – 它的用来修饰 Inherited,意味着 Inherited 实现了 java.lang.annotation.Annotation 接口;即 Inherited 就是一个注解。

  • @Documented – 它的作用是说明该注解能出现在 javadoc 中。

  • @Retention(RetentionPolicy.RUNTIME) – 它的作用是指定 Inherited 的策略是 RetentionPolicy.RUNTIME。这就意味着,编译器会将 Inherited 的信息保留在 .class 文件中,并且能被虚拟机读取。

  • @Target(ElementType.ANNOTATION_TYPE) – 它的作用是指定 Inherited 的类型是 ANNOTATION_TYPE。这就意味着,@Inherited 只能被用来标注 “Annotation 类型”。

  • @Inherited 的含义是,它所标注的Annotation将具有继承性。例如:假设定义了某个 Annotaion,它的名称是 MyAnnotation,并且 MyAnnotation 被标注为 @Inherited。现在,某个类 Base 使用了

    MyAnnotation,则 Base 具有了"具有了注解 MyAnnotation";现在,Sub 继承了 Base,由于 MyAnnotation 是 @Inherited的(具有继承性),所以,Sub 也 “具有了注解 MyAnnotation”。

3.@SuppressWarnings

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    String[] value();
}

说明:

  • @interface – 它的用来修饰 SuppressWarnings,意味着 SuppressWarnings 实现了 java.lang.annotation.Annotation 接口;即 SuppressWarnings 就是一个注解。

  • @Retention(RetentionPolicy.SOURCE) – 它的作用是指定 SuppressWarnings 的策略是 RetentionPolicy.SOURCE。这就意味着,SuppressWarnings 信息仅存在于编译器处理期间,编译器处理完之后 SuppressWarnings 就没有作用了。

  • @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) – 它的作用是指定 SuppressWarnings 的类型同时包括TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE。

  • TYPE 意味着,它能标注"类、接口(包括注释类型)或枚举声明"。

  • FIELD 意味着,它能标注"字段声明"。

  • METHOD 意味着,它能标注"方法"。

  • PARAMETER 意味着,它能标注"参数"。

  • CONSTRUCTOR 意味着,它能标注"构造方法"。

  • LOCAL_VARIABLE 意味着,它能标注"局部变量"。

  • String[] value(); 意味着,SuppressWarnings 能指定参数

  • SuppressWarnings 的作用是,让编译器对"它所标注的内容"的某些警告保持静默。例如,“@SuppressWarnings(value={“deprecation”, “unchecked”})” 表示对"它所标注的内容"中的 "SuppressWarnings 不再建议使用警告"和"未检查的转换时的警告"保持沉默。

SuppressWarnings常用关键字:

关键字含义
deprecation使用了不赞成使用的类或方法时的警告
unchecked执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型
fallthrough当 Switch 程序块直接通往下一种情况而没有 Break 时的警告
path在类路径、源文件路径等中有不存在的路径时的警告
serial当在可序列化的类上缺少 serialVersionUID 定义时的警告
finally任何 finally 子句不能正常完成时的警告
all关于以上所有情况的警告

5、注解作用

1、编译检查

例如,@SuppressWarnings, @Deprecated 和 @Override 都具有编译检查作用。

若某个方法被 @Override 的标注,则意味着该方法会覆盖父类中的同名方法。如果有方法被 @Override 标示,但父类中却没有"被 @Override 标注"的同名方法,则编译器会报错。

2、反射中使用

在反射的 Class, Method, Field 等函数中,有许多于 Annotation 相关的接口。

这也意味着,我们可以在反射中解析并使用 Annotation。例子如下:

public class AnnotationTest {
    public static void main(String[] args) throws Exception{
        //新建Person
        Person person = new Person();
        //获取Person的Class实例
        Class<Person> c = Person.class;
        //获取 somebody()方法的Method实例
        Method mSomebody = c.getMethod("somebody", new Class[]{String.class, int.class});
        //执行该方法
        mSomebody.invoke(person, new Object[]{"zhangsan", 18});
        iteratorAnnotations(mSomebody);

        //获取empty()方法的Method实例
        Method mEmpty = c.getMethod("empty", new Class[]{});
        //执行该方法
        mEmpty.invoke(person, new Object[]{});
        iteratorAnnotations(mEmpty);
    }

    public static void iteratorAnnotations(Method method) {
        //判断方法是否包含MyAnnotation注解
        if(method.isAnnotationPresent(MyAnnotation.class)){
            //获取该方法的MyAnnotation注解实例
            MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
            //获取myAnnotation的值,并打印出来
            String[] values = myAnnotation.value();
            for(String str:values) {
                System.out.printf(str + " ");
            }
            System.out.println();
        }

        // 获取方法上的所有注解,并打印出来
        Annotation[] annotations = method.getAnnotations();
        for(Annotation annotation : annotations){
            System.out.println(annotation);
        }
        System.out.println();
    }
}

/**
 * 创建一个注解
 */
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    String[] value() default "unknown";
}

/**
 * Person类,会使用到MyAnnotation注解
 */
class Person{
    /**
     * empty()方法同时被 "@Deprecated" 和 "@MyAnnotation(value={"a","b"})"所标注
     * @Deprecated,意味着empty()方法,不再被建议使用
     * @MyAnnotation, 意味着empty() 方法对应的MyAnnotation的value值是默认值"unknown"
     */
    @MyAnnotation
    @Deprecated
    public void empty(){
        System.out.println("empty");
    }

    /**
     * sombody() 被 @MyAnnotation(value={"girl","boy"}) 所标注
     * @MyAnnotation(value={"girl","boy"}), 意味着MyAnnotation的value值是{"girl","boy"}
     * @param name
     * @param age
     */
    @MyAnnotation(value = {"girl", "boy"})
    public void somebody(String name, int age){
        System.out.println("somebody:" + name + ",age:" + age);
    }
}

运行结果:

somebody:zhangsan,age:18
girl boy 
@MyAnnotation(value=[girl, boy])

empty
unknown 
@MyAnnotation(value=[unknown])
@java.lang.Deprecated()
3、生成帮助文档

通过给 Annotation 注解加上 @Documented 标签,能使该 Annotation 标签出现在 javadoc 中。

6、自定义注解

1.定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Name {
    String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Sex {
    GenderType gender() default GenderType.Male;
    
    public enum GenderType {
        Male("男"),
        Female("女");
        
        private String genderStr;
        
        GenderType(String arg0) {
            this.genderStr = arg0;
        }
        
        @Override
        public String toString() {
            return genderStr;
        }
    }
}

2.将自定义注解标注在属性上

public class Person {
    
    @Name(value = "so_cool")
    private String name;
    
    private int age;
    
    @Sex(gender = Sex.GenderType.Male)
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

3、获取注解标注的属性

public class AnnotationTest {
    public static void main(String[] args) {
        String info = getInfo(Person.class);
        System.out.println(info);
    }

    public static String getInfo(Class<?> cs){
        String result = "";
        //获取全部属性
        Field[] declaredFields = cs.getDeclaredFields();
        for (Field field : declaredFields){
            //判断属性是否包含@Name注解
            if(field.isAnnotationPresent(Name.class)){
                //获取注解信息
                Name annotation = field.getAnnotation(Name.class);
                //获取注解标注的内容
                String value = annotation.value();
                result += (field.getName() + ":" + value + "\n");
            }
            if(field.isAnnotationPresent(Sex.class)){
                Sex annotation = field.getAnnotation(Sex.class);
                String value = annotation.gender().name();
                result += (field.getName() + ":" + value + "\n");
            }
        }
        return result;
    }
}

4、打印结果

name:so_cool
sex:Male
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值