[英]Create java method that only accepts non-abstract Class types
In Java, is it possible to create a method / a signature that accepts all non-abstract Class types?在 Java 中,是否可以创建一个接受所有非抽象 Class 类型的方法/签名?
Something a la this:这有点像:
public Object getInstance(Class<? extends ConcreteClassSuperType> someNonAbstractClass){
//some logic that can safely assume that the Class object is not an interface type nor an abstract class
}
where ConcreteClassSuperType
is just a fictional type made up to illustrate my intend.其中
ConcreteClassSuperType
只是为了说明我的意图而虚构的类型。 Using ? extends Object
使用
? extends Object
? extends Object
here does not solve the problem.在这里
? extends Object
并不能解决问题。
Elaboration: In the case at hand the problem was a bit more specific in that my signature dit not have to accept ALL concrete classes but only those implementing some interface, ie I was trying to create a signature that accepts the Class type of a class that implements MyInterface
.详细说明:在手头的情况下,问题更具体一点,因为我的签名不必接受所有具体的类,而只接受那些实现某些接口的类,即我试图创建一个接受 Class 类型的 class 类型的签名
implements MyInterface
。 So one could fx pass MyClass.class
, where MyClass implements MyInterface
.所以人们可以通过
MyClass.class
,其中MyClass implements MyInterface
。 Two problems occured:出现了两个问题:
MyInterface.class
(since the generics Class<? extends MyInterface>
is not a strict upper bound)MyInterface.class
(因为 generics Class<? extends MyInterface>
不是严格的上限)extends MyInterface
.extends MyInterface
的另一个接口的 class 类型。Because classes can have multiple parameters, I think it is easier first just to check if the class is concrete and then implement a means to instantiate it.因为类可以有多个参数,我认为首先检查 class 是否具体,然后实现实例化它更容易。 Like,
喜欢,
public <T> boolean isConcrete(Class<T> c) {
if (c.isInterface() || (c.getModifiers() & Modifier.ABSTRACT) == Modifier.ABSTRACT)
return false;
return true;
}
Hope this helps.希望这可以帮助。
EDIT编辑
Sorry just noticed in another comment you could simplify this...抱歉刚刚在另一条评论中注意到你可以简化这个......
public <T> boolean isConcrete(Class<T> c) {
if (c.isInterface() || Modifier.isAbstract(c.getModifiers()))
return false;
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.