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
  • 相关阅读:
    重定向输出流实现程序日志
    为新员工分配部门
    从控制台接收输入的身份证号
    判断某一年是否为闰年
    linux重置mysql密码(root权限)
    mysql按照字符串类型的数值按数值进行排序
    android 下拉刷新
    android studio gradle 配置
    搭建自己的iOS内测分发平台
    http_range说明
  • 原文地址:https://www.cnblogs.com/mature1021/p/9568075.html
Copyright © 2011-2022 走看看