2013-11-20 65 views
2

为什么我无法将对象转换为通过参数提供的类类型?如何传递类类型作为参数并将其转换为参数?

public static checkInstanceOf(Object obj, Class<?> type) { 
    return obj instanceof type; //error: type cannot be resolved to a type 
} 

我想创建一个实用程序方法,必须在更详细的例程中使用像这样的instanceof检查。我需要改变什么?

我希望能够调用是这样的:

MyUtil.checkInstanceOf(new String(""), MyClass.class); 

回答

4

您要使用的Class类的isInstance方法。

+0

太好了。另一个问题:我是否也可以将我的对象投影到该实例? – membersound

+0

帮助你自己[文档](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html)。 –

+0

铸造是编译时的事情。你的意思是“转换”? –

相关问题