>  기사  >  Java  >  Java 사용자 정의 주석의 자세한 예 및 리플렉션을 사용한 주석 읽기

Java 사용자 정의 주석의 자세한 예 및 리플렉션을 사용한 주석 읽기

巴扎黑
巴扎黑원래의
2017-09-08 09:35:551222검색

아래 편집기는 Java 사용자 정의 주석의 예와 리플렉션을 사용하여 주석을 읽는 예를 제공합니다. 편집자님이 꽤 좋다고 생각하셔서 지금 공유하고 모두에게 참고용으로 드리고자 합니다. 편집기를 따라 살펴보겠습니다

1. 사용자 정의 주석

메타 주석:

@interface 주석: 주석 인터페이스 정의

@Target 주석: 설명된 주석의 사용을 제한하는 데 사용됩니다. 범위, 설명된 주석이 사용 범위를 초과하면 컴파일이 실패합니다. 예: ElementType.METHOD,ElementType.TYPE;

@Retention 주석: 정의된 주석의 범위를 제한하는 데 사용됩니다.

1 범위는 다음과 같습니다. 소스 코드, Java 파일에 대해 작동하고 javac가 실행될 때 주석을 제거합니다.

2. RetentionPolicy.CLASS: 범위는 클래스 파일에 존재하는 바이너리 코드입니다. 이 주석은 Java가 실행될 때 제거됩니다.

3. RetentionPolicy.RUNTIME: 범위는 런타임입니다. 즉, 주석을 동적으로 얻을 수 있습니다.

@Documented: javadoc이 API 문서를 생성할 때 표시되도록 이 주석을 지정하는 데 사용됩니다.

@Inherited

: 는 설명된 주석이 설명하는 클래스의 하위 클래스에서 상속될 수 있음을 지정하는 데 사용됩니다. 기본값은 해당 주석이 해당 하위 클래스에서 상속될 수 없다는 것입니다.

사용자 정의 주석 인터페이스:


package com.java.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD,ElementType.TYPE})
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Annotation_my {
 
 String name() default "张三";//defalt 表示默认值
 
 String say() default "hello world";
 
 int age() default 21;
 
}

다음으로 인터페이스를 정의합니다.


package com.java.annotation;

@Annotation_my //使用我们刚才定义的注解
public interface Person {
 
 @Annotation_my
 public void name();
 
 @Annotation_my
 public void say();
 
 @Annotation_my
 public void age();

}

인터페이스가 정의된 후 인터페이스의 구현 클래스를 작성할 수 있습니다(인터페이스는 인스턴스화할 수 없습니다).


package com.java.annotation;

@Annotation_my
@SuppressWarnings("unused")
public class Student implements Person {
 
 private String name;

 @Override
 @Annotation_my(name="流氓公子") //赋值给name 默认的为张三
//在定义注解时没有给定默认值时,在此处必须name赋初值
 public void name() {
  
 }


 @Override
 @Annotation_my(say=" hello world !")
 public void say() {
  
 }

 @Override
 @Annotation_my(age=20)
 public void age() {
  
 }
}

그런 다음 주석을 테스트하기 위한 테스트 클래스를 작성하겠습니다


package com.java.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Text {
 Annotation[] annotation = null;

 public static void main(String[] args) throws ClassNotFoundException {
  new Text().getAnnotation();
 }
 
 public void getAnnotation() throws ClassNotFoundException{
  Class<?> stu = Class.forName("com.java.annotation.Student");//静态加载类
  boolean isEmpty = stu.isAnnotationPresent(com.java.annotation.Annotation_my.class);//判断stu是不是使用了我们刚才定义的注解接口if(isEmpty){
   annotation = stu.getAnnotations();//获取注解接口中的
   for(Annotation a:annotation){
    Annotation_my my = (Annotation_my)a;//强制转换成Annotation_my类型
    System.out.println(stu+":\n"+my.name()+" say: "+my.say()+" my age: "+my.age());
   }
  }
  Method[] method = stu.getMethods();//
  System.out.println("Method");
  for(Method m:method){
   boolean ismEmpty = m.isAnnotationPresent(com.java.annotation.Annotation_my.class);
   if(ismEmpty){
    Annotation[] aa = m.getAnnotations();
    for(Annotation a:aa){
     Annotation_my an = (Annotation_my)a;
     System.out.println(m+":\n"+an.name()+" say: "+an.say()+" my age: "+an.age());
    }
   }
  }
  //get Fields by force
  System.out.println("get Fileds by force !");
  Field[] field = stu.getDeclaredFields();
  for(Field f:field){
   f.setAccessible(true);
   System.out.println(f.getName());
  }
  System.out.println("get methods in interfaces !");
  Class<?> interfaces[] = stu.getInterfaces();
  for(Class<?> c:interfaces){
   Method[] imethod = c.getMethods();
   for(Method m:imethod){
    System.out.println(m.getName());
   }
  }
 }

}

위 내용은 Java 사용자 정의 주석의 자세한 예 및 리플렉션을 사용한 주석 읽기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.