Skip to content

Commit

Permalink
优化reflecutil
Browse files Browse the repository at this point in the history
  • Loading branch information
leaderli committed Aug 19, 2024
1 parent 5ffdcb0 commit d7136be
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,24 @@ public class ReflectUtil {

private static final ReflectionAccessor REFLECTION_ACCESSOR = ReflectionAccessor.getInstance();

/**
* 根据对象和{@link Field}获取字段值
*
* @param object 对象实例,如果为null,表示获取静态字段
* @param field 字段
* @return 字段值的Lino包装, 如果找不到字段或字段值为空, 返回{@link Lino#none()}
*/
public static Lino<?> getFieldValue(Object object, Field field) {


if (field == null) {
return Lino.none();
}

setAccessible(field);
return Lino.ofIgnoreError(() -> field.get(object));
}

/**
* 可以获取对象中的指定字段的值
*
Expand All @@ -43,6 +61,14 @@ public static Lino<?> getFieldValue(Object obj, String name) {
return getField(clazz, name).unzip(f -> getFieldValue(obj, f));
}

public static Lino<?> getStaticFieldValue(Class<?> clazz, Field field) {
return getFieldValue(null, field);
}

public static Lino<?> getStaticFieldValue(Class<?> clazz, String name) {
return getField(clazz, name).unzip(f -> getStaticFieldValue(clazz, f));
}

/**
* 可以获取指定类中的指定字段
*
Expand Down Expand Up @@ -110,24 +136,6 @@ public static Lino<Field> getField(Class<?> clazz, Function<Field, Boolean> filt
}


/**
* 根据对象和{@link Field}获取字段值
*
* @param object 对象实例,如果为null,表示获取静态字段
* @param field 字段
* @return 字段值的Lino包装, 如果找不到字段或字段值为空, 返回{@link Lino#none()}
*/
public static Lino<?> getFieldValue(Object object, Field field) {


if (field == null) {
return Lino.none();
}

setAccessible(field);
return Lino.ofIgnoreError(() -> field.get(object));
}

/**
* 设置对象的可访问性
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
*/
@SuppressWarnings("ALL")
class ReflectUtilTest {
static int a = 1;
static {
WhenThrowBehavior.WHEN_THROW = null;

Expand Down Expand Up @@ -136,6 +137,8 @@ void getFieldValue() throws NoSuchFieldException {

assertEquals(1, (ReflectUtil.getFieldValue(littleBean, "gender").get()));

assertEquals(1, ReflectUtil.getStaticFieldValue(this.getClass(), "a").get());

}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ static <T> MethodProxy<T> of(T value) {
return (m, args) -> value;
}

static <T> MethodProxy<T> error(Throwable throwable) {
return (m, args) -> {
throw throwable;
};
}

/**
* @return 根据返回类型生成一个默认值
*/
Expand Down

0 comments on commit d7136be

Please sign in to comment.