Last active
August 29, 2015 14:04
-
-
Save wisaruthk/09b56a56d941be6e955b to your computer and use it in GitHub Desktop.
My Java Annotation Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package my; | |
import java.lang.reflect.Field; | |
import my.annotation.MyColumn; | |
public class Main { | |
public static void main(String[] args) { | |
MyObject o = new MyObject("Jonathan", "Jo", "GREEN"); | |
//อีกเทคนิคหนึ่งที่ใช้ร่วมกับ Annotation คือ reflect เพื่อเรียกดูข้อมูลของ Class | |
Class klazz = o.getClass(); | |
//ดู field ทั้งหมดที่ประกาศ | |
for (Field f : klazz.getDeclaredFields()) { | |
MyColumn myCol = f.getAnnotation(MyColumn.class); | |
if (myCol != null) | |
System.out.println( | |
"anno_name:" + myCol.name()+ | |
",field_name:"+f.getName()); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package my.annotation; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
@Retention(RetentionPolicy.RUNTIME) //กำหนดว่าใช้เวลา Runtime | |
@Target({ElementType.FIELD}) //กำหนดว่าใช้กับ Field | |
public @interface MyColumn { | |
String name(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package my; | |
import my.annotation.MyColumn; | |
public class MyObject { | |
@MyColumn(name = "COL_NAME") | |
private String name; | |
@MyColumn(name = "COL_NICKNAME") | |
private String nickname; | |
@MyColumn(name = "COL_COLOR") | |
private String color; | |
public MyObject() { | |
} | |
public MyObject(String name, String nickname, String color) { | |
this.name = name; | |
this.nickname = nickname; | |
this.color = color; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public String getNickname() { | |
return nickname; | |
} | |
public void setNickname(String nickname) { | |
this.nickname = nickname; | |
} | |
public String getColor() { | |
return color; | |
} | |
public void setColor(String color) { | |
this.color = color; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment