Amit
Amit

Reputation: 539

Passing an instance of type Class instead of the class represented by Class

Let us say there is a class X. Then, the following line returns an instance of Class which represents X

Class c = X.class;

Assume there is a method foo()

public void foo(X x){.....}

Is it legitimate to do

foo(c);

Upvotes: 1

Views: 58

Answers (2)

mhlz
mhlz

Reputation: 3547

No. foo expects an instance of the class X, but your c variable is an instance of the class Class!

Try to think of it this way:

The foo method wants to do something with a house (for example locking the door or something like that). You want to give it the blueprint to the house instead of an actual house! Yes, the blueprint of the house and the house itself are closely related but they're not the same thing. You can't lock the door in the blueprint but only on the real house.

Likewise there are certain things that you can only do with a blueprint but not with a real house, e.g. building another house like the first one.

In your case you could use the newInstance method to try and create a new object with type X or use other methods of the Class object to find and invoke other constructors. This type of "meta" programming is called reflection and you can find out more about it here: https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/index.html

Upvotes: 2

M A
M A

Reputation: 72844

No, X is a type. Class is a different type. The foo method expects an object to the type represented by the Class instance, not the Class instance itself. You would have to create an instance of the type represented by the Class:

Class<X> c = X.class;
X x = c.newInstance();
foo(x);

Upvotes: 2

Related Questions