什么是 Java 对象 getClass() 方法?
Java 使用Object类提供的名为getClass()的方法来获取所使用的任何对象的类。方法头
public final Class<?> getClass()
该方法不带任何参数,而是在需要获取其类的对象上调用。
返回类型
该方法返回“对象”的类。例子
public class DriverClass {
public static void main(String[] args) {
Object myObject = 25;
Class myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = Float.NaN;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = Short.MIN_VALUE;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = 37.99999999000099990;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = Long.MAX_VALUE;
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
myObject = "This is a String.";
myObjectClass = myObject.getClass();
System.out.println("Class of \"" + myObject + "\" = " + myObjectClass.getName());
}
}
输出
“25”的类 = java.lang.Integer “NaN”的类 = java.lang.Float “-32768”的类 = java.lang.Short “37.999999990001”的类 = java.lang.Double “9223372036854775807”的类= java.lang.Long “这是一个字符串”的类。= java.lang.String
GO TO FULL VERSION