類名.class, class.forName(), getClass()區別

綜述:


1)Class cl=A.class; JVM將使用類A的類裝載器,將類A裝入內存(前提是:類A還沒有裝入內存),不對類A做類的初始化工作.返回類A的Class的對象
2)Class cl=對象引用o.getClass();返回引用o運行時真正所指的對象(因爲:兒子對象的引用可能會賦給父對象的引用變量中)所屬的類的Class的對象 
3)Class.forName("類名"); .裝入類A,並做類的初始化


getClass()是動態的,其餘是靜態的。

.class class.forName()只能返回類內field的默認值,getClass可以返回當前對象中field的最新值

Class.forName(xxx.xx.xx) 返回的是一個類, .newInstance() 後才創建一個對象 Class.forName(xxx.xx.xx);的作用是要求JVM查找並加載指定的類,也就是說JVM會執行該類的靜態代碼段 


代碼如下:

待反射類:

package yerasel;

public class Person {
	private String name = "Alfira";
	public void getName() {
		System.out.println(name);
	}
	public void setName(String name, int a) {
		this.name = name + a;
	}
}

反射代碼:

package yerasel;

import java.lang.reflect.Method;

public class Test {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		show("yerasel.Person");
	}

	private static void show(String name) {
		// TODO Auto-generated method stub
		try {
			// JVM將使用類A的類裝載器,將類A裝入內存(前提是:類A還沒有裝入內存),不對類A做類的初始化工作
			Class classtype3 = Person.class;
			// 獲得classtype中的方法
			Method getMethod3 = classtype3.getMethod("getName", new Class[] {});
			Class[] parameterTypes3 = { String.class, int.class };
			Method setMethod3 = classtype3
					.getMethod("setName", parameterTypes3);

			// 實例化對象,因爲這一句纔會輸出“靜態初始化”以及“初始化”
			Object obj3 = classtype3.newInstance();
			// 通過實例化後的對象調用方法
			getMethod3.invoke(obj3); // 獲取默認值
			setMethod3.invoke(obj3, "Setting new ", 3); // 設置
			getMethod3.invoke(obj3); // 獲取最新
			System.out.println("----------------");

			// 返回運行時真正所指的對象
			Person p = new Person();
			Class classtype = p.getClass();// Class.forName(name);
			// 獲得classtype中的方法
			Method getMethod = classtype.getMethod("getName", new Class[] {});
			Class[] parameterTypes = { String.class, int.class };
			Method setMethod = classtype.getMethod("setName", parameterTypes);
			getMethod.invoke(p);// 獲取默認值
			setMethod.invoke(p, "Setting new ", 1); // 設置
			getMethod.invoke(p);// 獲取最新
			System.out.println("----------------");

			// 裝入類,並做類的初始化
			Class classtype2 = Class.forName(name);
			// 獲得classtype中的方法
			Method getMethod2 = classtype2.getMethod("getName", new Class[] {});
			Class[] parameterTypes2 = { String.class, int.class };
			Method setMethod2 = classtype2
					.getMethod("setName", parameterTypes2);
			// 實例化對象
			Object obj2 = classtype2.newInstance();
			// 通過實例化後的對象調用方法
			getMethod2.invoke(obj2); // 獲取默認值
			setMethod2.invoke(obj2, "Setting new ", 2); // 設置
			getMethod2.invoke(obj2); // 獲取最新

			System.out.println("----------------");

		} catch (Exception e) {
			System.out.println(e);
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章