Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Class<SomeObject> have only one instance?

Tags:

java

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?

like image 383
Alexander Kulyakhtin Avatar asked Sep 11 '15 11:09

Alexander Kulyakhtin


Video Answer


2 Answers

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)
    }
    ...
}
like image 169
Victor Avatar answered Oct 31 '22 22:10

Victor


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).

like image 45
Kayaman Avatar answered Oct 31 '22 23:10

Kayaman