Java 例項說明 獲得一個類的類物件有哪些方式?
阿新 • • 發佈:2019-01-08
例子:
public class StaticStuff {
public static void main(String[] args) {
StaticStuff heStaticStuff = new StaticStuff();
System.out.println(StaticStuff.class);
System.out.println(heStaticStuff.getClass());
try {
System.out.println(Class.forName("com.lz.crm.StaticStuff"));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
執行結果:
class com.lz.crm.StaticStuff
class com.lz.crm.StaticStuff
class com.lz.crm.StaticStuff
三種方式:
- 方法1:型別.class,例如:String.class
- 方法2:物件.getClass(),例如:"hello".getClass()
- 方法3:Class.forName(),例如:Class.forName("java.lang.String")