Signature of the Object.getClass () method

The class object contains the following method:

public final Class<? extends Object> getClass().

why the return type of this method Class<? extends Object>

+3
source share
5 answers

Since Java is missing self types . (If they were with them, then the return type would be Class<? extends self_type>). Thus, the signature simply declares Class<?>, (the next one) the best thing it can do, which is less than ideal - the compiler certainly knows that it is getClass()not returning any class, and the class, which is a subtype of / strong> of the static type of the expression, is which is called getClass().

, , Class<?> - , Class<? extends TheClass>, , :)

PS: Class<? extends Object>, getClass() Object.

+3

JDK 1.5. . this bugreport. , , :

List<String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass()); // Incompatible types?

1.6, Class<?> Class<? extends Object>.

+2

? extends Object Java, Object. Java Object, pathpath. Class<? extends Object> Object.getClass() - , , , .

+1

( , 1.6)

public final Class<?> getClass()

javadocs:

- , | X | getClass. , :

n = 0;
<? extends Number > c = n.getClass();

, , , . ,

Class c = n.getClass(); //c now has no type information
+1

getClass() () ,

MyClass myClass1 = new MyClass();
MyClass myClass2 = new MyClass();

if (myClass.getClass().equals(myClass2.getClass())
{
  // do stuff
}

- , . Object, Java.

getClass() - getName(),

myClass1.getClass().getName() 

MyClass

string className = myClass1.getClass().getName();
MyClass newInstance = (MyClass) Class.forName(className).newInstance();
0

Source: https://habr.com/ru/post/1753208/


All Articles