5

Does Class<SomeObject> have only one instance which is SomeObject.class?

That is to a function

void f(Class<SomeObject> arg)

is it possible to pass only SomeObject.class otherwise compile time error?

Alexander Kulyakhtin
  • 47,782
  • 38
  • 107
  • 158

4 Answers4

8

Yes.

As describe at the documentation:

Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

But for the method void f(Class<SomeObject> arg) you can pass something as void f(Class<? extends SomeObject> arg). Look this question.

Passing an Class<? extends SomeObject arg you can do something like that:

myMethod(Class<? extends BasicObject> clazz)
{
    if (!clazz.isInstance(CodeObject))
    {
        (do something different)
    }
    ...
}
Community
  • 1
  • 1
Victor
  • 8,309
  • 14
  • 80
  • 129
  • Thank you! So, would that be meaningless to define void f(Class arg) as it would only accept SomeObject.class? – Alexander Kulyakhtin Sep 11 '15 at 11:41
  • No! SomeObject can be extended, so If you have an extended object you can handle this on the method. – Victor Sep 11 '15 at 11:43
  • 1
    @Alex It may seem meaningless, but it can be useful in some special scenarios. For example if you had class `MyClass` with `init(Class clazz)` method and then you would extend from it, or something like that. – kajacx Sep 11 '15 at 11:43
3

You can always pass null, but barring that, yes the only valid parameter would be SomeObject.class which is loaded with the same ClassLoader as the class that contains void f(Class<SomeObject> clazz).

You can have multiple distinct instances of SomeObject.class, but they will need to be loaded by different classloaders (otherwise they will not be separate instances, but all will refer to the same Class object).

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0
  1. Yes

  2. maybe You thing in this way?

    Class< ? extends SomeObject>

this is notation for class of SomeObject or overrides (something wrong with syntax highlighter, don't accept ?, space between < ? is not required)

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22
0

It does seems true that each class has only one corresponding Class instance, see this discussion

Your method could also be invoked by a raw Class argument :) unfortunately.

Class clazz = AnotherClass.class;

f(clazz); 
Community
  • 1
  • 1
ZhongYu
  • 19,446
  • 5
  • 33
  • 61