由於工作需求要應用到java反射機制,就做了一下功能demo想到這些就做了一下記錄
這個demo目的是實現動態獲取到定時器的方法好注解名稱,廢話不多說了直接上源碼
1.首先需要自定義注解類
/**
* 自定義方法注解 此時用於定時器注解便於生成方法以及方法的作用
* (獲取定時器任務的方法以及名稱)
*/
@Documented
@Target({ElementType.METHOD}) //注解應用類型(應用到方法的注解,還有類的可以自己試試)
@Retention(RetentionPolicy.RUNTIME) // 注解的類型
public @interface MethodInterface {
//屬性字段名稱 默認空字符串
String name() default "";
}
2.創建好自定方法類名就可以創建了
public class TestThtread {
public final Integer NUMBER = 100000;
@MethodInterface(name = "方法注解1")
public void test1(){
System.out.println("方法體1");
}
@MethodInterface(name = "方法注解2")
public void test2(){
System.out.println("方法體2");
}
@MethodInterface(name = "方法注解3")
public void test3(){
System.out.println("方法體3");
}
}
3.最后就是利用java反射機制獲取了
public static void testJava() {
Class<?> printClass = null;
//KeyValueDto是實體類方便返回也可以用map
List<KeyValueDto> list = new ArrayList();
try {
//獲取類名的包名地址
printClass = Class.forName("com.lxp.demo.Schedules.TestThtread");
//java反射機制獲取所有方法名
Method[] declaredMethods = printClass.getDeclaredMethods();
//遍歷循環方法並獲取對應的注解名稱
for (Method declaredMethod : declaredMethods) {
String isNotNullStr = "";
// 判斷是否方法上存在注解 MethodInterface
boolean annotationPresent = declaredMethod.isAnnotationPresent(MethodInterface.class);
if (annotationPresent) {
// 獲取自定義注解對象
MethodInterface methodAnno = declaredMethod.getAnnotation(MethodInterface.class);
// 根據對象獲取注解值
isNotNullStr = methodAnno.name();
}
list.add(new KeyValueDto(declaredMethod.getName(),isNotNullStr));
}
//排序(按照方法名稱排序)
Collections.sort(list);
System.out.println(list.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
實體類 KeyValueDto
public class KeyValueDto implements Comparable<KeyValueDto>{
private String key;
private String value;
public KeyValueDto(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public int compareTo(KeyValueDto o) {
return o.getKey().compareTo(this.key);
}
@Override
public String toString() {
return "{" +
"key='" + key + '\'' +
", value='" + value + '\'' +
'}';
}
}
4.最后一步就是測試和結果了
public static void main(String[] args) {
testJava();
}
看完這個是不是感覺java反射機制很清晰,我就感覺很強大,雖然這個是冰山一角,但是這個也是花了點時間就分享一下,有興趣可以留言討論下更多的