Java Class isAnnotationPresent()方法

java.lang.Class.isAnnotationPresent(Class<T> annotationClass) 方法用于检查此类中是否存在指定注释类型的注释。该方法返回一个声明相同的布尔值。

1 语法

public boolean isAnnotationPresent(Class<T> annotationClass)

2 参数

annotationClass:要获取的注释的类型。

3 返回值

返回声明相同的布尔值。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Class isAnnotationPresent()方法
 */
// Java program to demonstrate 
// isAnnotationPresent() method 
  
import java.util.*; 
import java.lang.annotation.*; 
  
// create a custom Annotation 
@Retention(RetentionPolicy.RUNTIME) 
@interface Annotation { 
  
    // This annotation has two attributes. 
    public String key(); 
  
    public String value(); 
} 
  
// call Annotation for method 
// and pass values for annotation 
@Annotation(key = "GFG", value = "GeeksForGeeks") 
public class Test { 
  
    public static void main(String[] args) 
        throws ClassNotFoundException 
    { 
  
        // returns the Class object for this class 
        Class myClass = Test.class; 
  
        System.out.println("Class represented by myClass: "
                           + myClass.toString()); 
  
        // Check if there is any annotation 
        // using isAnnotationPresent() method 
        System.out.println( 
            "If there is any annotation in myClass: "
            + myClass.isAnnotationPresent( 
                  Annotation.class)); 
    } 
}

输出结果为:

Class represented by myClass: class Test
If there is any annotation in myClass: true

 

热门文章

优秀文章