How to understand the Object.getClass () method?

The Object.getClass()javadoc Java method says:

Returns the execution class of this Object. The returned object is an Classobject that is locked by the methods static synchronizedrepresented by the class. The actual type of result Class<? extends |X|>where |X|is the erasure of the static type of the expression on which getClass. For example, in this code no throwing snippet is required:

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

Returns: an object Classthat represents the execution class of this object.

What is the execution class?

What does "returned object Class... static synchronizedmethod locked " mean?

+4
source share
3 answers

getClass Class , , .

, , . , , , List, ;

static void foo(List l) {
    System.out.println(l.getClass().getName());
}

:

foo(new LinkedList()); // Outputs "java.util.LinkedList"
foo(new ArrayList());  // Outputs "java.util.ArrayList"

foo List, (!) , , getClass , .

?

static synchronized Class, , . , foo notThreadSafe, , :

// On thread 1
Foo.notThreadSafe();

// On thread 2
Foo.notThreadSafe();

, notThreadSafe synchronized:

public static synchronized void notThreadSafe() { 
    /* ... */
}

public static void notThreadSafe() { 
    synchronized (Foo.class) {
        /* ... */
    }
}

(Foo.class Class foo.)

, 1 , 2 ( - Foo.class), .

; static synchronized (m1 m2), 1 m1, 2 m2, m2 m1, ( Class foo).

getClass()? Class - , getClass foo :

System.out.println(Foo.class == (new Foo()).getClass()); // true
+3

"Runtime class" - , . , :

Object o = new String();
System.out.println(o.getClass());

class java.lang.String, , o - String. .

" ", , , ThisClass:

public static synchronized foo() {
    ...
}

... :

public static foo() {
    synchronized(ThisClass.class) {
        ...
    }
}

Class . .

+1

For your second question, this means using:

class A {}
class B extends A {
  public static synchronized void f() {}
}
...
A a = new B();
Class <? extends A> c = a.getClass();

a call f()to c(only possible through reflection) will effectively use the same lock as B.f(). The lock will be an object of the class.

0
source

All Articles