Does the <SomeObject> class have only one instance?

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

That is, for the function

void f(Class<SomeObject> arg)

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

+5
source share
4 answers

You can always pass null , but by denying that the only valid parameter is SomeObject.class , which loads with the same ClassLoader as the class containing void f(Class<SomeObject> clazz) .

You may have several different instances of SomeObject.class , but you will need to load them with different class loaders (otherwise they will not be separate instances, but they will all refer to the same class object).

+3
source

Yes.

As described in the documentation :

Returns the execution class of this object. The returned class object is an object that is blocked by the static synchronized methods of the class represented.

But for the void f(Class<SomeObject> arg) method, you can pass something like void f(Class<? extends SomeObject> arg) . Check out this question .

Passing Class<? extends SomeObject arg Class<? extends SomeObject arg , you can do something like this:

 myMethod(Class<? extends BasicObject> clazz) { if (!clazz.isInstance(CodeObject)) { (do something different) } ... } 
+8
source
  • Yes

  • Maybe you do that?

    Class <? extends SomeObject>

this is a designation for the SomeObject class or overriding (something is wrong with the syntax label, don’t accept ?, a space between <? is not required)

0
source

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

Unfortunately, your method can also be called with the original Class argument.

 Class clazz = AnotherClass.class; f(clazz); 
0
source

All Articles