文章目录
1.反射
反射在平时的开发中很少用,但是在处理代码的灵活性上非常具有帮助,反射获取对应类的字节码,动态代理也利用了反射的机制。如spring中xml的配置模式,转载bean,springboot中在properties或者yml中配置属性转化为对应的实体。
2.反射的三种方式
新建一个User.
public class User {
private String UserName;
private int age;
private String address;
}
2.1 通过new对象实现反射机制
User user = new User("elite",12,"XX");
Class userClass = user.getClass();
Constructor[] constructors = userClass.getConstructors();
for(Constructor c: constructors){
User o = (User) c.newInstance("elite",12,"xx");
System.out.println(o.showUserInfo());
}
2.2 通过路径实现反射机制
@Test
public void Test2() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class clazz= Class.forName("com.elite.java.reflection.User");
System.out.println(clazz.getName());
Constructor<User> constructor = clazz.getConstructor(new Class[]{String.class,Integer.class,String.class});
User user = constructor.newInstance("elite2", 12, "xxxx");
System.out.println(user.showUserInfo());
}
2.3 通过类名实现反射机制
@Test
public void Test3() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
Class clazz= User.class;
System.out.println( clazz.getName());
Constructor<User> constructor = clazz.getConstructor(new Class[]{String.class,Integer.class,String.class});
User user = constructor.newInstance("elite3", 12, "xxxx");
System.out.println(user.showUserInfo());
}
3.利用反射减少代码量
实际开发中,特别是银行类支付参数串,大部分需要填补位置,填充0或者空格之类的。
比如金额字段,10位,两位小数,不足10位前面补充0填位。这个自定义注解,利用反射来实现想要的结果。
自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface BankPayParams {
//其他的可以自己定义
int Length();
}
定义请求参数对象
/**
* 银行支付请求参数
*/
public class BankPayRqInfo {
/**
* 支付金额
*/
@BankPayParams(Length = 10)
public BigDecimal money;
}
组织参数测试
/**
* 测试反射
*/
@Test
public void Test4() throws IllegalAccessException {
//设置构造请求参数对象
BankPayRqInfo rqInfo = new BankPayRqInfo(new BigDecimal("10.00"));
String params = FormatParams(rqInfo);
System.out.println(params);
}
private String FormatParams(BankPayRqInfo rqInfo) throws IllegalAccessException {
StringBuilder sb = new StringBuilder();
for(Field field:rqInfo.getClass().getDeclaredFields()){
//获取字段对应的注解
BankPayParams p = field.getDeclaredAnnotation(BankPayParams.class);
if(p!=null){
// 获取Field的值:
Object value = field.get(rqInfo);
// 如果值是String:
if (value instanceof BigDecimal) {
String s = value.toString();
if (s.contains(".")) s = s.replace(".","");
int Length = p.Length();
String format = StringUtils.leftPad(s,Length,"0");
sb.append(format);
}
}
}
return sb.toString();
}