java Annotation

1.getDeclaredMethods() 和getMethods()的區別html

 getDeclaredMethods()
   返回 Method 對象的一個數組,這些對象反映此 Class 對象表示的類或接口聲明的全部方法,包括公共、保護、默認(包)訪問和私有方法,但不包括繼承的方法。 java

 getMethods()
   返回一個包含某些 Method 對象的數組,這些對象反映此 Class 對象所表示的類或接口(包括那些由該類或接口聲明的以及從超類和超接口繼承的那些的類或接口)的公共 member 方法。android

2.Class.forName()用法數組

Class.forName(xxx.xx.xx)返回的是一個類
Class.forName(xxx.xx.xx)的做用是要求JVM查找並加載指定的類,
也就是說JVM會執行該類的靜態代碼段


3.cls.isAnnotationPresent(myAnnotation1.class);//判斷該類是不是參數中類的註解,是true,否false
4.舉例學習Annotation

import java.lang.annotation.Documented;ide

import java.lang.annotation.ElementType;學習

import java.lang.annotation.Retention;this

import java.lang.annotation.RetentionPolicy;spa

import java.lang.annotation.Target;code

 

@Target(ElementType.TYPE)htm

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface myAnnotation1 {

 String value();

}

import java.lang.annotation.Documented;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)   //這句若是沒有,後面就檢測不到該Annotation

@Documented

public @interface myAnnotation2 {  

String description();

boolean isAnnotation(); }

 

@myAnnotation1("this is annotation1")

public class AnnotationDemo {  

@myAnnotation2(description = "this is annotaion2", isAnnotation = true)

 public void sayHello() {   System.out.println("hello world!");

 }

}

package com.mmscn.test2;

import java.lang.reflect.Method;

import android.util.Log;

public class TestAnnotation {  

public void test() throws ClassNotFoundException, NoSuchMethodException {

  Class<?> cls = Class.forName("com.mmscn.test2.AnnotationDemo");

  boolean flag = cls.isAnnotationPresent(myAnnotation1.class);  

 Log.i("flag", "=====" + flag);  

 if (flag) {   

 System.out.println("判斷類是annotation");   

 myAnnotation1 annotation1 = cls.getAnnotation(myAnnotation1.class);    

System.out.println(annotation1.value());  

 }

  Method method = cls.getMethod("sayHello");

  Log.i("method", "=====*****" + method.getName());   

flag = method.isAnnotationPresent(myAnnotation2.class);  

 Log.i("flag", "=====*****" + flag);   

if (flag) {    

System.out.println("判斷方法也是annotation");    

myAnnotation2 annotation2 = method.getAnnotation(myAnnotation2.class);   

 System.out.println(annotation2.description() + "===-=="      + annotation2.isAnnotation());  

 }  }

 public TestAnnotation() {

  // TODO Auto-generated constructor stub  }

}

 

public class MainActivity extends Activity {

 

 @Override  

protected void onCreate(Bundle savedInstanceState) {   

super.onCreate(savedInstanceState);  

 setContentView(R.layout.activity_main);  

 TestAnnotation atestAnnotation = new TestAnnotation();   

try {    

atestAnnotation.test();   

}

catch (ClassNotFoundException e) {    

// TODO Auto-generated catch block    

e.printStackTrace();   

} catch (NoSuchMethodException e) {  

  // TODO Auto-generated catch block    

e.printStackTrace();   }  }}

相關文章
相關標籤/搜索