Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the type of an object so that I can use it with instanceof?

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

like image 962
Nosrettap Avatar asked Dec 21 '25 11:12

Nosrettap


1 Answers

Try this instead:

if(c1.isInstance(o))
{
    // ...
}
like image 131
Eng.Fouad Avatar answered Dec 24 '25 01:12

Eng.Fouad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!