JAVA反射机制获取实体类对象的属性和数据类型以及属性值

    /**
     * 遍历实体类的属性和数据类型以及属性值
     * @param model
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     */
    public static void reflectTest(Object model) throws NoSuchMethodException,
                    IllegalAccessException, IllegalArgumentException,
                    InvocationTargetException {
        // 获取实体类的所有属性,返回Field数组
        Field[] field = model.getClass().getDeclaredFields();
        // 遍历所有属性
        for (int j = 0; j < field.length; j++) {
                // 获取属性的名字
                String name = field[j].getName();
                // 将属性的首字符大写,方便构造get,set方法
                name = name.substring(0, 1).toUpperCase() + name.substring(1);
                // 获取属性的类型
                String type = field[j].getGenericType().toString();
                // 如果type是类类型,则前面包含"class ",后面跟类名
                System.out.println("属性为:" + name);
                if (type.equals("class java.lang.String")) {
                        Method m = model.getClass().getMethod("get" + name);
                        // 调用getter方法获取属性值
                        String value = (String) m.invoke(model);
                        System.out.println("数据类型为:String");
                        if (value != null) {
                                System.out.println("属性值为:" + value);
                        } else {
                                System.out.println("属性值为:空");
                        }
                }
                if (type.equals("class java.lang.Integer")) {
                        Method m = model.getClass().getMethod("get" + name);
                        Integer value = (Integer) m.invoke(model);
                        System.out.println("数据类型为:Integer");
                        if (value != null) {
                                System.out.println("属性值为:" + value);
                        } else {
                                System.out.println("属性值为:空");
                        }
                }
                if (type.equals("class java.lang.Short")) {
                        Method m = model.getClass().getMethod("get" + name);
                        Short value = (Short) m.invoke(model);
                        System.out.println("数据类型为:Short");
                        if (value != null) {
                                System.out.println("属性值为:" + value);
                        } else {
                                System.out.println("属性值为:空");
                        }
                }
                if (type.equals("class java.lang.Double")) {
                        Method m = model.getClass().getMethod("get" + name);
                        Double value = (Double) m.invoke(model);
                        System.out.println("数据类型为:Double");
                        if (value != null) {
                                System.out.println("属性值为:" + value);
                        } else {
                                System.out.println("属性值为:空");
                        }
                }
                if (type.equals("class java.lang.Boolean")) {
                        Method m = model.getClass().getMethod("get" + name);
                        Boolean value = (Boolean) m.invoke(model);
                        System.out.println("数据类型为:Boolean");
                        if (value != null) {
                                System.out.println("属性值为:" + value);
                        } else {
                                System.out.println("属性值为:空");
                        }
                }
                if (type.equals("class java.util.Date")) {
                        Method m = model.getClass().getMethod("get" + name);
                        Date value = (Date) m.invoke(model);
                        System.out.println("数据类型为:Date");
                        if (value != null) {
                                System.out.println("属性值为:" + value);
                        } else {
                                System.out.println("属性值为:空");
                        }
                }
                if (type.equals("double")) {
                    Method m = model.getClass().getMethod("get" + name);
                    double value = (double) m.invoke(model);
                    System.out.println("数据类型为:double");
                    if (value >0) {
                            System.out.println("属性值为:" + value);
                    } else {
                            System.out.println("属性值为:空");
                    }
                }
        }
    }

 setter与getter方法拼装与调用

// 拼装setter方法
Method m1 = hr.getClass().getMethod("setDay"+day,Double.class);
// 拼装getter方法
Method m2 = hr.getClass().getMethod("getDay"+day);
// 调用getter方法
Double da =  (Double) m2.invoke(hr);
// 调用setter方法
m1.invoke(hr,da);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要定义一个自定义注解,用于标记需要翻译的字段。注解中需要定义一个属性,用于指定需要翻译的字典类型。示例代码如下: ```java @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Translation { String dictType(); } ``` 接下来,我们需要定义一个字典管理器,用于将字典数据读取到内存中,并提供翻译方法。示例代码如下: ```java public class DictionaryManager { private Map<String, Map<String, String>> dictMap; public DictionaryManager() { dictMap = new HashMap<>(); } public void loadDictionary(String dictType, String dictFilePath) throws IOException { Map<String, String> dict = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(Paths.get(dictFilePath))) { String line; while ((line = reader.readLine()) != null) { String[] parts = line.split(","); if (parts.length == 2) { dict.put(parts[0], parts[1]); } } } dictMap.put(dictType, dict); } public String translate(String dictType, String key) { Map<String, String> dict = dictMap.get(dictType); if (dict != null) { return dict.get(key); } return null; } } ``` 在字典管理器中,我们使用了一个Map来存储字典数据,key为字典类型,value为字典数据。loadDictionary方法用于将字典数据从文件中读取到内存中。translate方法用于根据字典类型和key翻译字典。 最后,我们需要编写一个注解处理器,用于处理标记了Translation注解的字段。注解处理器需要在程序启动时初始化字典管理器,并将需要翻译的字段的翻译后设置到对应的字段中。示例代码如下: ```java public class TranslationProcessor { private DictionaryManager dictManager; public TranslationProcessor() { dictManager = new DictionaryManager(); } public void init() throws IOException { // 加载字典数据 dictManager.loadDictionary("gender", "gender_dict.txt"); dictManager.loadDictionary("region", "region_dict.txt"); } public void process(Object obj) { Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { Translation translation = field.getAnnotation(Translation.class); if (translation != null) { field.setAccessible(true); try { String dictType = translation.dictType(); String dictValue = (String) field.get(obj); String translatedValue = dictManager.translate(dictType, dictValue); if (translatedValue != null) { Field targetField = obj.getClass().getDeclaredField(field.getName() + "_translated"); targetField.setAccessible(true); targetField.set(obj, translatedValue); } } catch (Exception e) { e.printStackTrace(); } } } } } ``` 在注解处理器中,我们首先加载字典数据。然后,通过反射获取对象的所有字段,遍历所有字段,如果字段标记了Translation注解,则获取该注解的dictType属性和字段的。接着,使用字典管理器翻译该字段的,并将翻译后的设置到对应的新字段中。最后,我们需要在程序启动时初始化注解处理器,示例代码如下: ```java public class App { public static void main(String[] args) throws IOException { TranslationProcessor processor = new TranslationProcessor(); processor.init(); // 示例对象 User user = new User(); user.setName("张三"); user.setGender("male"); user.setRegion("110101"); // 处理对象 processor.process(user); // 输出翻译后的结果 System.out.println(user.getName()); System.out.println(user.getGender_translated()); System.out.println(user.getRegion_translated()); } } ``` 以上就是一个简单的使用自定义注解和反射实现字典翻译的示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值