Custom annotations for java reflection

Source: Internet
Author: User

Java User-Defined annotation. It is convenient for programmers to obtain and process information using reflection. Let alone code.

Import static java. lang. annotation. ElementType. FIELD;
Import static java. lang. annotation. RetentionPolicy. RUNTIME;


Import java. lang. annotation. Annotation;
Import java. lang. annotation. Retention;
Import java. lang. annotation. Target;
Import java. lang. reflect. Field;


Import org. junit. Test;


Public class MyAnotation {


@ Test
Public void testMyAnotation ()
{
MySubObject mySub = new MySubObject ();
MySub. setProperty1 ("property1111 ");
MySub. setProperty2 ("property222 ");

Field [] fields = mySub. getClass (). getDeclaredFields ();
For (Field field: fields)
{
Annotation ano = field. getAnnotation (Sub. class );
If (ano! = Null)
{
System. out. println (field. getName ());
Sub sub = (Sub) ano;
System. out. println (sub. name ());
System. out. println (sub. type ());
}
}
}
@ Retention (RUNTIME)
@ Target ({FIELD })
// This annotation acts on the object's domain
Public @ interface Sub {
Public String name ();
// Name attribute
Public String type ();
// Type attribute
}

Public class MySubObject {
@ Sub (name = "mysubname", type = "mysubtype ")
Private String property1;
Private String property2;
Public String getProperty1 (){
Return property1;
}
Public void setProperty1 (String property1 ){
This. property1 = property1;
}
Public String getProperty2 (){
Return property2;
}
Public void setProperty2 (String property2 ){
This. property2 = property2;
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.