주석을 읽는 방법과 작업이 없으면 주석이 주석보다 더 유용하지 않습니다. 주석 사용 프로세스의 중요한 부분은 주석 프로세서를 사용하여 작성됩니다. Javase5는 반사 메커니즘 API를 확장하여 프로그래머가 사용자 정의 주석 프로세서를 신속하게 구성 할 수 있도록 도와줍니다.
주석이 달린 프로세서 클래스 라이브러리 (java.lang.reflect.annotatedElement) :
Java는 주석 인터페이스를 사용하여 모든 주석 유형의 부모 인터페이스 인 프로그램 요소 앞에서 주석을 나타냅니다. 또한 Java는 java.lang.reflect 패키지 아래에 AnnotatedElement 인터페이스를 추가했습니다. 이 인터페이스는 프로그램의 주석을 수용 할 수있는 프로그램 요소를 나타냅니다. 인터페이스에는 주로 다음 구현 클래스가 있습니다.
클래스 : 수업 정의
생성자 : 생성자 정의
필드 : 누적 멤버 변수 정의
방법 : 클래스의 메소드 정의
패키지 : 클래스의 패키지 정의
java.lang.reflect 패키지에는 주로 반사 기능을 구현하는 일부 도구 클래스가 포함되어 있습니다. 실제로 Java.Lang.Refrect 패키지가 제공하는 모든 반사 API는 런타임 주석 정보를 읽는 기능을 확장합니다. 주석 유형이 런타임에 주석으로 정의되면 런타임시 주석을 볼 수 있으며 클래스 파일을로드 할 때 클래스 파일에 저장된 주석은 가상 시스템에서 읽습니다.
AnnotatedElement 인터페이스는 모든 프로그램 요소 (클래스, 메소드 및 생성자)의 상위 인터페이스입니다. 따라서 프로그램이 반사를 통해 특정 클래스의 주석이없는 객체를 얻은 후, 프로그램은 다음 4 가지 방법을 호출하여 주석 정보에 액세스 할 수 있습니다.
메소드 1 : <TextEndannotation> tgetAntantation (class <t> annotationClass) : 프로그램 요소에 존재하는 지정된 유형의 주석을 반환합니다. 유형의 주석이 존재하지 않으면 null을 반환하십시오.
방법 2 : 주석 [] getAnnotations () : 프로그램 요소에 존재하는 모든 주석을 반환합니다.
메소드 3 : BooleanisAnnotationPresent (class <? extendAntantation> 주석 클래스) : 프로그램 요소에 지정된 유형의 주석이 포함되어 있는지 여부를 결정합니다. 존재하면 true를 반환하고 그렇지 않으면 거짓을 반환합니다.
메소드 4 : 주석 [] getDeclaredAnnotations () :이 요소에 직접 존재하는 모든 주석을 반환합니다. 이 인터페이스의 다른 방법과 달리이 방법은 상속 된 주석을 무시합니다. (이 요소에 직접 주석이 없으면 길이 0의 배열이 반환됩니다.)이 메소드의 발신자는 반환 된 배열을 마음대로 수정할 수 있습니다. 이것은 다른 발신자가 반환 한 배열에 영향을 미치지 않습니다.
간단한 주석 프로세서 :
/*********************** 주석 선언 ******************* // ***과일 이름 주석*@Author peida*/ @target (eleMpertype.field) @Retention (rendentionPolicy.runtime) @documentedPublic @Interface friftName {String Value () Default "; */ @target (ElementType.field) @retention (rendentionpolicy.runtime) @documentedPublic @Interface fruitColor {/** * 색상 enum * @Author peida */public enum color {bule, green};/** * 컬러 속성 * @return */color fruitcolor () default Color ()/** **}/** supplier}; @author peida*/ @target (elementtype.field) @retention (retentionpolicy.runtime) @documentedpublic @interface fruitprovider {/*** 공급 업체 번호*/public int id () 기본값 -1;/*** 공급 업체 이름*/public string name () defat ";/** @@return*/public string (); "";}/******************* : 주석 사용 ***********************/public class apple {@fruitname ( "Apple") 개인 문자열 애플리닝; @fruitcolor (fruitcolor = color.red) 비공개 문자열 applecolor; @fruitprovider (@fruitprovider (id = = 1, name = "shaanxi hongfuji, hongfuji. 89, Shaanxi Province, Xi'an City ")) 개인 문자열 AppleProvider; public void setapplecolor (String applecolor) {this.applecolor = applecolor;} public String getApplecolor () {return applecolor;} public void setapplename (string applename) {this.applename; getApPleName () {return ApplEname;} public void setAppleProvider (String AppleProvider) {this.appleProvider = AppleProvider;} public String getAppleProvider () {return AppleProvider;} public void displayName () {System.out.println ( "Fruit.}/***************}}}}}}}}} 프로세서 *************************/public class fruitinfoutil {public static void getfruitinfo (class <?> clazz) {String strfruitname = "fruit name :"; String strfruitcolor = "fruit color :"; strfruitprovicer = "공급 업체 정보 :"; fielddecledd (finddecledd); : fields) {if (field.isannotationPresent (fruitname.class)) {fruitname fruitname = (fruitname) field.getAntation (fruitname.class); strfruitname = strfruitname+fruitname.value (); system.out.println (strfruitname);} else if (field.isannotationPresent (fruitcolor.class)) {FruitColor FruitColor = (FruitColor) Field.getAntantation (fruitColor.class); strfruitColor = strfruitColor+FriendColor.fruitColor (). toString (); SystrFuitColor); if (field.isannotationPresent (fruitprovider.class)) {FruitProvider FruitProvider = (FruitProvider) Field.getAnnotation (fruitprovider.class); strfruitprovicer = "공급 업체 번호 :"+fruitprovider.id ()+"공급 업체 이름 :"+fruitprovider.name ()+"공급 업체 :"공급 업체 : " "+fruitProvider.address();System.out.println(strFruitProvicer);}}}}/*************** Output result****************************/public class FruitRun {/** * @param args */public static void main(String[] args) {fruitinfoutil.getfruitinfo (apple.class);}}}}}}} ============================================================== Apple 과일 색상 : 공급 업체 이름 : 1 공급 업체 이름 : Shaanxi Hongfuji Hongfuji Building, No. 89, Yan'an Road, Xi'an City, Shaanxi Province기본적으로 Java 주석의 기본 지식 포인트를 읽었습니다 (아래지도 참조). 다음 기사에서는 주석을 기반으로 간단한 ORM 프레임 워크를 설계하여 주석의 다양한 지식 지점의 이해와 적용을 종합적으로 적용하고 더욱 심화시킵니다.
요약
위의 내용은이 기사에서 Java Annotation 프로세서의 간단한 예제에 관한 모든 것입니다. 모든 사람에게 도움이되기를 바랍니다. 관심있는 친구는이 사이트의 다른 관련 주제를 계속 참조 할 수 있습니다. 단점이 있으면 메시지를 남겨 두십시오. 이 사이트를 지원해 주신 친구들에게 감사드립니다!