如何获取对象的类型以便我可以将其与instanceof一起使用?

Nos*_*tap 2 java reflection

我正在用Java编写程序,我有一个带有标题的方法,public void doSomething(Object o)我想检查o是否是另一个方法的参数的合适类型.所以我拥有的是:

public void doSomething(Object o)
{
    Method m = //get method of another method (using reflection)
    Class<?> cl = m.getParameterTypes()[0];  //Get the class of the 0th parameter
    if(o instanceof cl)         //compile error here
         //do something
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.请有人帮忙吗.谢谢

Eng*_*uad 5

试试这个:

if(c1.isInstance(o))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)