利用JDK提供的反射工具类,可实现简单的Java Bean的属性赋值、获取属性值、获取所有属性及指定属性名的属性等。文章来源地址https://www.toymoban.com/news/detail-857448.html
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public final class ReflectionUtils {
public static Field getField(Class<?> cls, String fieldName) {
Class<?> sCls = cls;
do {
try {
return sCls.getDeclaredField(fieldName);
} catch (NoSuchFieldException ignored) {
sCls = sCls.getSuperclass();
}
} while (!Object.class.equals(sCls));
throw new RuntimeException("no such field[" + fieldName + "] in class [" + cls + "]");
}
public static Field getField(Object obj, String fieldName) {
return getField(obj.getClass(), fieldName);
}
public static List<Field> getAllFields(Class<?> cls) {
List<Field> fields = new ArrayList<>();
Class<?> sCls = cls;
do {
fields.addAll(Arrays.asList(sCls.getDeclaredFields()));
sCls = sCls.getSuperclass();
} while (!Object.class.equals(sCls));
return fields;
}
public static List<Field> getAllFields(Object obj) {
return getAllFields(obj.getClass());
}
public static void set(Object obj, Field f, Object v) {
try {
f.set(obj, v);
} catch (IllegalAccessException e) {
f.setAccessible(true);
try {
f.set(obj, v);
} catch (IllegalAccessException ignored) {
}
}
}
public static void set(Object obj, String fieldName, Object v) {
set(obj, getField(obj, fieldName), v);
}
public static Object get(Object obj, Field f) {
try {
return f.get(obj);
} catch (IllegalAccessException e) {
try {
f.setAccessible(true);
return f.get(obj);
} catch (IllegalAccessException ignored) {
return null;
}
}
}
public static Object get(Object obj, String fieldName) {
return get(obj, getField(obj, fieldName));
}
}
文章来源:https://www.toymoban.com/news/detail-857448.html
到了这里,关于一个Java反射小工具的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!