0

Note: I am not asking what types can be used to store a class name nor I am asking for work-arounds to store class names such as reflection or using Strings. This is also not a question on asking how to use instanceof operator.

Consider this example:

A a = new A();
Class c1 = A.class;
System.out.println(a instanceof c1);    //Does not Work

Class c2 = A.class.getClass();
System.out.println(a instanceof c2);    //Does not Work

class A{}

I know the above codes will fail. But I am curious whether it is possible to store a class such that it can work as though I am typing out the class name itself.

System.out.println(a instanceof A);    //This will work

Can we hold (class)A with some variables xx so that this will work?

System.out.println(a instanceof xx);   

My question is: Is it possible to store A with a variable such that the compiler will treat that variable as though it is seeing A?

Note: I am not asking how to store object of A. I am asking is it possible to store A itself.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
user3437460
  • 17,253
  • 15
  • 58
  • 106
  • You mean like [this](http://stackoverflow.com/questions/949352/is-there-something-like-instanceofclass-c-in-java)? – rbennett485 Jan 18 '15 at 13:26
  • You need to use `Class.isAssignableFrom`. Read the [JavaDoc for `Class`](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html). – Boris the Spider Jan 18 '15 at 13:26

2 Answers2

5

You cannot use the instanceof operator. The second operand of instanceof must be a class name, it cannot be an arbitrary expression, in particular, it cannot be a variable.

The grammar states that the syntax for instanceof is:

RelationalExpression:
    RelationalExpression instanceof ReferenceType

And ReferenceType can only be the name of a class or interface, an array type or a type variable (not a normal variable). So, it doesn't matter which type you use to declare that variable you can't achieve what you want due to a fundamental limitation of the (current) grammar.

Also instanceof has to perform some checks at compile-time and, hence, it must be able to determine which type you want to use as second operand at compile-time, but using an expression would allow to change that type dynamically at runtime.

However you can use the dynamic equivalent, the isInstance method:

System.out.println(c1.isInstance(a));

The documentation explictly says so:

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.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
1

Use this for the general case:

System.out.println(c1.isAssignableFrom(a.getClass()));

Or this for the instance:

System.out.println(c1.isInstance(a));
Bohemian
  • 412,405
  • 93
  • 575
  • 722