1

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);
Amit
  • 519
  • 1
  • 5
  • 20

2 Answers2

2

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);
M A
  • 71,713
  • 13
  • 134
  • 174
2

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

mhlz
  • 3,497
  • 2
  • 23
  • 35
  • OK. The main thing is that there is no kind of inheritance relationship between an instance of Class and the class represented by Class. – Amit Jun 24 '15 at 08:15
  • Sort of. The difference between a class and an instance of that class goes much further than that though. – mhlz Jun 24 '15 at 11:55
  • Maybe reading [this](http://stackoverflow.com/questions/13775226/what-is-the-difference-between-classes-and-object-instances) will help you understand a bit more ^.^ – mhlz Jun 24 '15 at 12:17