在java中使用反射是常规操作,我们经常需要面对未知的属性或者经过层层代理或者委派等情况下的属性值,在不能给对方定性的基础上,我们就可以采用一刀切的方式去解决问题。毕竟根本的这些属性均在于与各个变形中。比如前些时候我们说的拦截器实现主从库抉择的问题。这块我们写几个反射的工具类已被后用!
代码语言:javascript复制public class FansheUtils {
static Field getDeclaredField(String clazz, String fieldName) throws ClassNotFoundException {
Field field=null;
Class clz = Class.forName(clazz);
//super class
for (Class<?> s = clz; s != Object.class; s = s.getSuperclass()) {
try {
field= s.getDeclaredField(fieldName);
field.setAccessible(true);
} catch (NoSuchFieldException ignored) {
}
}
return field;
}
public static <T> T getFieldValue(Object object, String fieldName) throws ClassNotFoundException {
Field field = getDeclaredField(object.getClass().getName() , fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field [" fieldName "] on target [" object "]");
}
Object result = null;
try {
result = field.get(object);
} catch (IllegalAccessException ignored) {
}
return (T) result;
}
public static void setFieldValue(Object object, String fieldName, Object value) throws ClassNotFoundException {
Field field = getDeclaredField(object.getClass().getName() , fieldName);
try {
//set public
if (field.isAccessible()) {
field.set(object, value);
} else {
//set privite
field.setAccessible(true);
field.set(object, value);
field.setAccessible(false);
}
} catch (IllegalAccessException ignored) {
}
}
protected Method getMethodByName(String methodName, Class<?> entityClazz) {
Method[] methods = entityClazz.getMethods();
Method method = null;
for (Method i : methods) {
if (methodName.equals(i.getName())) {
method = i;
break;
}
}
return method;
}
}
测试一下:
代码语言:javascript复制public class TestFanshe {
static class Test{
private String name;
private int age;
@Override
public String toString() {
return "TestFanshe{"
"name='" name '''
", age=" age
'}';
}
}
public static void main(String[] args) throws ClassNotFoundException {
Test test=new Test();
String name=FansheUtils.getFieldValue(test,"name");
System.out.println(name);
FansheUtils.setFieldValue(test,"name","tianjingle");
FansheUtils.setFieldValue(test,"age",1);
System.out.println(test.toString());
}
}
午安~