创建@Interfa: package com.easygo.server; 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; @Documented @Inherited @Target({ ElementType.FIELD, ElementType.METHOD })//允许属性和方法 @Retention(RetentionPolicy.RUNTIME)//允许通过反射加载, public @interface Mature { String value() default ""; } User类: package com.easygo.server; public class User { @Mature(value="mature") public String userName; public String getUserName() { return userName; } @Mature(value="mature")//使用自定义注解, public void setUserName(String userName) { this.userName = userName; } } 通过Java反射实现自定义注解对象数据封装: package com.easygo.server; import java.lang.reflect.Method; import org.junit.Test; public class TestDome { @SuppressWarnings("rawtypes") public Object createUser() throws Exception { //通过反射获取User对象 String pack="com.easygo.server.User"; Class classz=Class.forName(pack); @SuppressWarnings("unchecked") Object user =classz.getConstructor().newInstance(); Method[]arr=classz.getMethods(); for(Method method:arr) { if(method.isAnnotationPresent(Mature.class)) {//判断方法是否存在注解 Mature mature=method.getAnnotation(Mature.class);//获取该自定义注解 method.invoke(user, mature.value());//将值赋值到user对象 } } return user; //最终返回被赋值的user对象 } @Test public void test() {//测试 try { User user=(User) createUser(); System.out.println("username:"+user.getUserName()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 运行: username:mature
Java自定义注解(通过反射)
猜你喜欢
转载自www.cnblogs.com/mature1021/p/9568075.html
今日推荐
周排行