写几个java反射工具方法
写点笔记
共 2926字,需浏览 6分钟
·
2021-08-24 08:05
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;
}
}
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());
}
}
午安~
评论