最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

querydsl - How can I get the value of the instance field form a QClass? - Stack Overflow

programmeradmin3浏览0评论

When generate Qclasses, they look like,

@Generated("com.querydsl.codegen.DefaultEntitySerializer")
public class QWhatever extends EntityPathBase<Whatever> {

    // ...

    public static final QWhatever whatever = new QWhatever("whatever");

    // ...
}

Is there any utility class/method for fetching the whatever field's value?

I wrote a utility class, and it works, yet I feel re-invented the wheel.

    @SuppressWarnings({"unchecked"})
    public static <T extends EntityPathBase<?>> T getInstance(final Class<T> entityPathBaseClass) {
        Objects.requireNonNull(entityPathBaseClass, "entityPathBaseClass is null");
        return (T) INSTANCESputeIfAbsent(
                entityPathBaseClass,
                k -> Arrays.stream(entityPathBaseClass.getDeclaredFields())
                        .filter(f -> {
                            final var modifiers = f.getModifiers();
                            if (!Modifier.isPublic(modifiers)) {
                                return false;
                            }
                            if (!Modifier.isStatic(modifiers)) {
                                return false;
                            }
                            if (!Modifier.isFinal(modifiers)) {
                                return false;
                            }
                            if (f.getType() != entityPathBaseClass) {
                                return false;
                            }
                            return true;
                        })
                        .findFirst()
                        .map(f -> {
                            if (!f.canAccess(null)) {
                                f.setAccessible(true);
                            }
                            return f;
                        })
                        .map(f -> {
                            try {
                                return f.get(null);
                            } catch (final IllegalAccessException iae) {
                                throw new RuntimeException("failed to get value of " + f, iae);
                            }
                        })
                        .orElseThrow(() -> new IllegalArgumentException(
                                "unable to find the instance field from " +
                                entityPathBaseClass
                        ))
        );
    }
发布评论

评论列表(0)

  1. 暂无评论