zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    disruptor架构三 使用场景 使用WorkHandler和BatchEventProcessor辅助创建消费者
    disruptor架构二
    disruptor架构一
    线程池基础二
    线程池基础一
    多线程集成设计模式--MasterWorker模式讲解(一)
    多线程集成设计模式--future模式
    线程基础9-quene讲解
    线程基础8-quene讲解
    hdu3613 Best Reward
  • 原文地址:https://www.cnblogs.com/mature1021/p/9568075.html
Copyright © 2011-2022 走看看