-2

I am learning RTTI in Java and I wrote a function like that:

static void select(Shape s, Class c)
{
   if(s instanceof c)
   s.setSelected(true);
}
//Calling function: select(shape0, Circle);

The problem is, I have no idea if passing Class as paremater is possible? Compilator says it's error, it can't find c. So I used different code to solve this problem:

static void select(Shape s,Object obj)
{
    if(s.getClass().equals(obj.getClass()))
    s.setSelected(true);
}
 //Calling function: select(shape0, new Circle());

But I was wondering if something like first example is possible?

Bouncer00
  • 123
  • 1
  • 4
  • 12
  • Take a look at this earlier question http://stackoverflow.com/questions/949352/is-there-something-like-instanceofclass-c-in-java – Ravi Kiran Sep 07 '14 at 10:05

1 Answers1

1

Use the isInstance or isAssignableFrom method of Class depending on your needs.

isInstance docs excerpt:

Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

isAssignableFrom docs excerpt:

Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Maybe it wasn't obvious from the answer. `isInstance` and `isAssignableFrom` are methods of the Class object. So it'll be something like `c.isInstance(s)`. – Giulio Franco Sep 07 '14 at 09:44