java--反射:使用反射和注解实现属性值注入

反射在java里面是必须学会的知识,特别是在框架里面。之前对反射有些模糊不清,现在通过写博客来记录自己学习反射的知识。下面实现一个demo:通过注解的方式给某个类的属性赋值。

  • 定义注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value=ElementType.FIELD)
public @interface Value {
	String value();
}
  • 定义User类
public class User {
	@Value("1")
	private Integer id;
	@Value("张三")
	private String username;
	@Value("123456")
	private String password;
	public  Integer getId() {
		return id;
	}
	public void setId( Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
	
}
  •  代码实现
public class FanSheApp {
	public static void main(String[] args) {
		try {
			User user = new User();
			System.out.println(user.getClass() == User.class);
			fgx();
			Class<?> clazz = Class.forName("hhy.javaboy.fanshe.User");
			Method[] methods = clazz.getDeclaredMethods();
			for(Method method : methods) {
				System.out.println(method.getName());
			}
			fgx();
			Method m0 = clazz.getDeclaredMethod("setPassword", String.class);
			m0.invoke(user, "123456");
			System.out.println(user.getPassword());
			fgx();
			//获取类属性字段
			Field[] declaredFields = clazz.getDeclaredFields();
			for(Field declaredField : declaredFields) {
				declaredField.setAccessible(true);
				//判断类型是否属于String类型
				if(declaredField.getType() == String.class) {
					//给这个属性赋值
					declaredField.set(user, declaredField.getAnnotation(Value.class).value());
				}else{
					//获取这个字段的类型,Integer,Long,Double....
					String typeSImpleName = declaredField.getType().getSimpleName();
					//获取这个类型中的类型转换方法,例如:parseInteger()、parseLong().....
					Method method = declaredField.getType().getMethod("parse"+fixparse(typeSImpleName), String.class);
					if(method != null) {
						//反射调用方法
						Object ret = method.invoke(null, declaredField.getAnnotation(Value.class).value().toString());
						//当前字段赋值
						declaredField.set(user, ret);
					}
				}
			}
			System.out.println(user.toString());
			fgx();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	static String fixparse(String type) {
		System.out.println(type);
		switch(type) {
			case "Integer": 
				return "Int";
			case "Double":
				return "Double";
			default : 
				return type;
		}
	}
	static void fgx() {
		System.out.println("------------");
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您解答关于Java自定义字典类、自定义注解反射注入字典到实体类的问题。 首先,自定义字典类是一种将一些常量或者枚举类型的封装在一起的方式。可以让代码更加易读、易维护。比如,我们可以定义一个字典类,用来存储一些常量,如: ``` public class GenderDict { public static final Integer MALE = 1; public static final Integer FEMALE = 2; } ``` 接下来,我们可以使用自定义注解来标记需要注入字典的实体类的属性上。比如,我们可以定义一个注解类,如: ``` @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Dictionary { String value(); } ``` 在该注解类中,我们使用@Retention和@Target注解来指定注解的保留策略和作用范围。同时,我们还可以使用value属性来指定注解,即该属性需要注入的字典的名称。 最后,我们可以使用反射机制,在运行时动态地将字典注入到实体类中。具体的实现方式如下: ``` public class DictionaryInjector { public static void injectDictionary(Object obj) throws IllegalAccessException { Class<?> clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Dictionary.class)) { Dictionary dict = field.getAnnotation(Dictionary.class); String dictName = dict.value(); String dictValue = getDictValue(dictName); field.setAccessible(true); field.set(obj, dictValue); } } } private static String getDictValue(String dictName) { // 从字典类中获取对应的字典 // 这里可以使用反射或者其他方式来实现 return GenderDict.MALE.equals(dictName) ? "男" : "女"; } } ``` 在上述代码中,我们首先使用Class对象获取实体类的所有属性,然后通过判断该属性是否被@Dictionary注解标记来确定是否需要注入字典。如果需要注入,则从注解中获取字典的名称,然后通过反射机制将字典注入到实体类的属性中。 最后,我们可以在代码中使用如下方式来注入字典: ``` public class User { @Dictionary("gender") private String gender; // getters and setters } public class Main { public static void main(String[] args) throws IllegalAccessException { User user = new User(); DictionaryInjector.injectDictionary(user); System.out.println(user.getGender()); // 输出 "男" } } ``` 在上述代码中,我们首先定义了一个User类,并在其中使用@Dictionary注解标记了gender属性。然后,在Main类中,我们创建了一个User对象,并调用DictionaryInjector类的injectDictionary方法来注入字典。最后,我们通过调用User对象的getGender方法来获取注入后的字典。 希望这能够帮助您解决问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值