class A {}
class B extends A {}
class C extends A {}
class Main {
public static void main(String args[]) {
C c = new C();
Class clazz = c.getClass();
System.out.println(clazz);
}
}
输出:
class C
您还可以比较两个Class实例,以查看两个对象是否属于同一类型。
class A {}
class B extends A {}
class C extends A {}
class Main {
public static void main(String args[]) {
B b = new B();
Class c1 = b.getClass();
C c = new C();
Class c2 = c.getClass();
System.out.println(c1 == c2);
}
}
Object instance = new SomeClass();
instance.getClass().getName(); //will return the name (as String) (== "SomeClass")
instance.getClass(); //will return the SomeClass' Class object
// Method #1
if (obj instanceof C)
;
// Method #2
if (C.class.isInstance(obj))
;
// Method #3
if (C.class.isAssignableFrom(obj.getClass()))
;
// Method #4
try {
C c = (C) obj;
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
// Method #5
try {
C c = C.class.cast(obj);
// No exception: obj is of type C or IT MIGHT BE NULL!
} catch (ClassCastException e) {
}
public <T> void print(T data) {
System.out.println(data.getClass().getName()+" => The data is " + data);
}
传递任何类型的数据,该方法将在调用它时打印您传递的数据类型。如
String str = "Hello World";
int number = 10;
double decimal = 10.0;
float f = 10F;
long l = 10L;
List list = new ArrayList();
print(str);
print(number);
print(decimal);
print(f);
print(l);
print(list);
以下是输出
java.lang.String => The data is Hello World
java.lang.Integer => The data is 10
java.lang.Double => The data is 10.0
java.lang.Float => The data is 10.0
java.lang.Long => The data is 10
java.util.ArrayList => The data is []