I’m writing a program in Java and I have a method with a header such as public void doSomething(Object o) and I want to check if o is the appropriate type for a parameter of another method. So what I have is:
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
}
However this doesn’t work. Can someone help please. Thanks
instanceoftakes a static type as a parameter, what you’re looking for is a dynamic check ifowill work as a parameter to the method;