java基礎源碼 (4)--reflect包-AnnotatedElement介面

來源:互聯網
上載者:User

標籤:ann   ++   byte   tin   chm   efi   sample   new   font   

 

介面:AnnotatedElement

 * Represents an annotated element of the program currently running in this * VM.  This interface allows annotations to be read reflectively.  All * annotations returned by methods in this interface are immutable and * serializable. The arrays returned by methods of this interface may be modified * by callers without affecting the arrays returned to other callers.  表示當前在此虛擬機器中啟動並執行程式的注釋元素,該介面允許反射讀取注釋,通過該介面方法返回的所有注釋
都是不可變並且可序列化。通過此介面的方法返回的陳列可以由呼叫著,而不會影響其他調用者返回陣列進行修改。
*/public interface AnnotatedElement { /** * Returns true if an annotation for the specified type * is <em>present</em> on this element, else false. This method * is designed primarily for convenient access to marker annotations.    如果此元素上存在指定類型的注釋,則返回true,否則返回false,該方法主要用於方便
    訪問標記注釋
*/ default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { return getAnnotation(annotationClass) != null; } /** * Returns this element‘s annotation for the specified type if * such an annotation is <em>present</em>, else null.   如果這樣的註解存在,就返回該註解,否則返回Null*/ <T extends Annotation> T getAnnotation(Class<T> annotationClass); /** * Returns annotations that are <em>present</em> on this element. *返回此元素上存在的註解 */ Annotation[] getAnnotations(); /** * Returns annotations that are <em>associated</em> with this element. 返回與此註解相關聯的註解*/ default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {    //預設的調用getDeclaredAnnotationsByte傳入annotationClass作為參數 T[] result = getDeclaredAnnotationsByType(annotationClass);    //如果返回的數組長度大於零,則返回數組,
    //如果返回的數組是零長度而這個AnnotationElement是一個類,
    //並且參數類型是可繼承的註解類型,並且該AnnotatedElement的AnnotatedElement是非空的
    //則返回結果是在父類上調用getAnnotationsByType的結果,具有annotationClass作為論證
    //否則返回零長度的數組
if (result.length == 0 && // Neither directly nor indirectly present this instanceof Class && // the element is a class AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable Class<?> superClass = ((Class<?>) this).getSuperclass(); if (superClass != null) { // Determine if the annotation is associated with the // superclass result = superClass.getAnnotationsByType(annotationClass); } } return result; } /** * Returns this element‘s annotation for the specified type if * such an annotation is <em>directly present</em>, else null.    如果這樣的註解直接存在,則返回指定類型的元素註解,否則返回null,此方法忽略繼承的註解*/ default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) { Objects.requireNonNull(annotationClass); // Loop over all directly-present annotations looking for a matching one for (Annotation annotation : getDeclaredAnnotations()) { if (annotationClass.equals(annotation.annotationType())) { //更強大,在編譯期間進行動態轉換 return annotationClass.cast(annotation); } } return null; } default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) { Objects.requireNonNull(annotationClass); return AnnotationSupport. getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()). collect(Collectors.toMap(Annotation::annotationType, Function.identity(), ((first,second) -> first), LinkedHashMap::new)), annotationClass); } /** * Returns annotations that are <em>directly present</em> on this element. * This method ignores inherited annotations.    返回直接存在於此元素上的注釋*/ Annotation[] getDeclaredAnnotations();}

 isAnnotationPresent方法的樣本:

@Retention(RetentionPolicy.RUNTIME)@interface Cus{    public String name();    public String value();}@Cus(name = "SampleClass",value = "Sample Class Annotation")class SampClass{    private String sampleFileld;@Cus(name = "sampleMethod",value = "sample Method Annotation")    public String sampleMethod(){        return "sample";    }    public String getSampleFileld(){        return sampleFileld;    }    public void setSampleFileld(String sa){        this.sampleFileld=sa;    }}public class AccessibleObjectDemo {    public static void main(String [] args) throws NoSuchMethodException {        AccessibleObject sampleMethod = SampClass.class.getMethod("sampleMethod");            System.out.println("sampleMethod.isAnnotationPresent:"+sampleMethod.isAnnotationPresent(Cus.class));        //輸出結果:sampleMethod.isAnnotationPresent:true    }}
getAnnotations()樣本:
@Retention(RetentionPolicy.RUNTIME)@interface Tt{    public String name();    public String value();}@Tt(name = "SampleClass",value = "Sample Class Annotation")class SampClass2{    private String sampleFileld;    @Tt(name = "sampleMethod",value = "sample Method Annotation")    public String sampleMethod(){        return "sample";    }    public String getSampleFileld(){        return sampleFileld;    }    public void setSampleFileld(String sa){        this.sampleFileld=sa;    }}public class AccessibleObjectDemo2 {    public static void main(String [] args) throws NoSuchMethodException {        AccessibleObject sampleMethod = SampClass2.class.getMethod("sampleMethod");        Annotation[] annotations = sampleMethod.getAnnotations();        for(int i=0;i<annotations.length;i++){            if(annotations[i] instanceof Tt){                Tt cus2= (Tt) annotations[i];                System.out.println(cus2.name());                System.out.println(cus2.value());                /*                輸出結果:                 sampleMethod                  sample Method Annotation                * */            }        }    }}

 

java基礎源碼 (4)--reflect包-AnnotatedElement介面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.