英文:
Obtaining type class from java class using reflections
问题
I currently have a setup like this:
public abstract class Configurable<T> {
//...
}
public class ConfigurableBoolean extends Configurable<Boolean> {
//...
}
I'm looking to obtain a Boolean class from ConfigurableBoolean but Integer on a ConfigurableInt (similar setup)
英文:
I currently have a setup like this:
public abstract class Configurable<T> {
//...
}
public class ConfigurableBoolean extends Configurable<Boolean> {
//...
}
I'm looking to obtain a Boolean class from ConfigurableBoolean but Integer on a ConfigurableInt (similar setup)
答案1
得分: 2
Here is the translated content:
如果它只是"一步"(你要检查的类型的直接父类是Configurable<C>
,其中C
是一个非参数化类),那么它就是
@SuppressWarnings("unchecked")
<T> Class<? extends T> getConfigType(Class<? extends Configurable<? extends T>> clazz) {
String err = "configuration type of " + clazz + " is too hard to find";
if (!(clazz.getGenericSuperclass() instanceof ParameterizedType)) throw new UnsupportedOperationException(err);
var configurable = (ParameterizedType) clazz.getGenericSuperclass();
if (configurable.getRawType() != Configurable.class) throw new UnsupportedOperationException(err);
var args = configurable.getActualTypeArguments();
if (args.length != 1 || !(args[0] instanceof Class)) throw new UnsupportedOperationException(err);
return (Class<? extends T>) args[0];
}
你可以修改这个来搜索"更深":递归查找父类,直到找到Configurable
,甚至可以跟踪类型参数的赋值,以处理类似于
class ConfigurableList<T> extends Configurable<List<T>> { }
class ConfigurableListBoolean extends ConfigurableList<Boolean> { }
但除此之外,这似乎能够处理你的情况。
英文:
If it's just "one step" (the direct superclass of the type you're inspecting is Configurable<C>
where C
is a non-parametrized class), then it's
@SuppressWarnings("unchecked") <T> Class<? extends T> getConfigType(Class<? extends Configurable<? extends T>> clazz) {
String err = "configuration type of " + clazz + " is too hard to find";
if(!(clazz.getGenericSuperclass() instanceof ParameterizedType)) throw new UnsupportedOperationException(err);
var configurable = (ParameterizedType)clazz.getGenericSuperclass();
if(configurable.getRawType() != Configurable.class) throw new UnsupportedOperationException(err);
var args = configurable.getActualTypeArguments();
if(args.length != 1 || !(args[0] instanceof Class)) throw new UnsupportedOperationException(err);
return (Class<? extends T>)args[0];
}
You could modify this to search "harder": recursing up the superclasses until it finds Configurable
, and maybe even tracking the assignments of type parameters so it can handle things like
class ConfigurableList<T> extends Configurable<List<T>> { }
class ConfigurableListBoolean extends ConfigurableList<Boolean> { }
but otherwise this seems to handle your case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论