JAva反射こまごましたノート

1477 ワード

1.クラスタイプ3のメソッドを取得するには:
(1)Class.forName(「完全パッケージ名.クラス名」);
(2)类名class 
(3)対象.getClass
2.変数をクラスタイプでインスタンス化するには:
クラスタイプ.newInstance()
eg: Class clazz = Class.forName("com.wuhx.Teacher");
     Teacher tc = clazz.newInstance();
学習コードメモ:
/**
	 * 
	 * @param obj     
	 * @throws Exception
	 */
	public static void learnReflect(Object obj) throws Exception{
		/*=========================     ===============================
		Field[] field = obj.getClass().getDeclaredFields();
		for(int i=0; i<field.length; i++){
			
			String priv = Modifier.toString(field[i].getModifiers()); //     
			String name = field[i].getName();                         //    
			String type = field[i].getType().getName();               //    
			System.out.println(priv+" "+type+ " "+name);
		}*/
		/*=========================    ===============================
		Method method = obj.getClass().getMethod("sayHello",String.class);
		method.invoke(obj,"wuhx");*/
		/*=========================  /     ===============================
		Field f = obj.getClass().getDeclaredField("teaName");//          obj      
		f.setAccessible(true); //       private     
		String fValue = (String) f.get(obj);
		System.out.println("teaName: "+fValue);
		
		f.set(obj, "     ");
		fValue = (String) f.get(obj);
		System.out.println("teaName: "+fValue);*/
	}