• Java自定义注解(通过反射)


    创建@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
  • 相关阅读:
    AtCoder ABC 129F Takahashi's Basics in Education and Learning
    AtCoder ABC 129E Sum Equals Xor
    UVA 511 Do You Know the Way to San Jose?
    UVA 12504 Updating a Dictionary
    [Poi2000] 病毒
    [loj10061] 最短母串
    [Poi2010] Antisymmetry
    校内集训20181003
    校内集训20181001
    校内集训20180925
  • 原文地址:https://www.cnblogs.com/mature1021/p/9568075.html
Copyright © 2020-2023  润新知