如何检查通用类型是否在java中实现特定类型的通用接口? [英] How to check if a generic type implements a specific type of generic interface in java?
问题描述
可能重复:
运行时的常规类型的局部变量
我刚刚接触Java泛型,来自.NET世界,我习惯于能够编写一个这样的方法:
I'm new to Java generics, and coming from a .NET world, I'm used to being able to write a method like this:
public void genericMethod<T>(T genericObject)
{
if (genericObject is IList<String>)
{
//Do something...
}
}
此方法接受通用类型的对象,该对象是否实现通用接口 IList<>
的特定版本,在这种情况下为 IList< String>
The method accepts an object of a generic type, and checks whether that object implements a specific version of the generic interface IList<>
, in this case, IList<String>
.
现在,在Java中,我可以这样做:
Now, in Java, I'm able to do this:
public <T> void genericMethod(T genericObject)
{
if (genericObject instanceof Set<?>)
{
//Do something...
}
}
但
Java不会 让我做 if(genericObject instanceof Set< String>)
Java does not let me do if (genericObject instanceof Set<String>)
从我知道的,因为类型擦除,通常在Java中,这将由一个类对象,我们将做类似下面的事情:
From what I know, because of type erasure, normally in Java this would be taken care of by a class object, and we would do something like the following:
public <T> void genericMethod(T genericObject)
{
Class<OurTestingType> testClass = OurTestingType.class;
if (genericObject.getClass() == testClass)
{
//Do something...
}
}
但是因为我检查的类型是一个通用接口,你不能这样做:
but since the type I'm checking for is a generic interface, you can't do this:
Class< Set< String>> testClass = Set< String> .class
那么,在Java中如何检查一个通用对象是否实现了设置< String>
?
So, how, in Java, do I check if a generic object implements the specific type of Set<String>
?
推荐答案
Java实现擦除,在运行时告诉如果 genericObject
是 Set< String>
的实例。保证这一点的唯一方法是使用你的泛型的边界,或者检查集合中的所有元素。
Java implements erasure, so there's no way to tell on runtime if genericObject
is an instance of Set<String>
or not. The only way to guarantee this is to use bounds on your generics, or check all elements in the set.
使用边界检查:
public <T extends SomeInterface> void genericMethod(Set<? extends T> tSet) {
// Do something with tSet here
}
使用迭代和类型检查:
public <T> void genericMethod(T t) {
Set<String> strs = new HashSet<String>();
Set<?> tAsSet;
if (t instanceof Set<?>) {
tAsSet = (Set<?>) t;
for (Object obj : tAsSet) {
if (obj instanceof String) {
strs.add((String) obj);
}
}
// Do something with strs here
} else {
// Throw an exception or log a warning or something.
}
}
编辑: Mark Peters的注释如下:如果你可以将它添加到你的项目,Guava也有你的方法:
As per Mark Peters' comment below, Guava also has methods that do this for you if you can add it to your project:
public <T> void genericMethod(T t) {
if (t instanceof Set<?>) {
Set<?> set = (Set<?>) t;
if (Iterables.all(set, Predicates.instanceOf(String.class))) {
Set<String> strs = (Set<String>) set;
// Do something with strs here
}
}
}
语句 Iterables.all(set,Predicates.instanceOf(String.class))
本质上与 set instanceof设置< String>
。
这篇关于如何检查通用类型是否在java中实现特定类型的通用接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!