1. 程式人生 > 實用技巧 >Java反射簡單程式碼記錄

Java反射簡單程式碼記錄

Java反射簡單程式碼記錄

java 反射

看程式碼就好

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test{

	public static void main(String[] args) throws Exception {
		Class<?> classFS = Class.forName("FanShe");
		
		/*
		 * Constructor 構造器相關的類
		 */
		
		// 用無參構造方法,建立例項物件
Object fs = classFS.newInstance(); // *************有參構造方法 Constructor<?> constructor = classFS.getConstructor(String.class); System.out.println("構造方法:"); Object object1 = constructor.newInstance("window10"); // ************* /* * Field 成員變數相關的類 */ // 獲取成員變數值 Field[] declaredFields = classFS.getDeclaredFields(); for
(int i = 0; i < declaredFields.length; i++) { Field field = declaredFields[i]; field.setAccessible(true); System.out.println("名字:" + field.getName() + " 型別:" + field.getType() + " 值:" + field.get(fs)); //field.get(fs)中的get(object obj)傳入的需要是建立的出來的例項物件 //就是用這個返回的object:classFS.newInstance();也可是object1這個例項物件
} /* * Method 方法相關的類 */ // 獲取執行方法 Method[] declaredMethods = classFS.getDeclaredMethods(); for (int i = 0; i < declaredMethods.length; i++) { Method method = declaredMethods[i]; System.out.print("方法名:" + method.getName() + " 方法執行:"); method.invoke(object1);//fs和object1是一樣的。 } } } class FanShe { String s1 = "World!"; String s2 = "java!"; private String s3 = "China"; public FanShe() { } public FanShe(String s) { System.out.println("Hi," + s); } void helloWorld() { System.out.println("hello " + s1); } void helloJava() { System.out.println("hello " + s2); } void helloChina() { System.out.println("hello " + s3); } void helloWeekend() { System.out.println("hello Weekend!"); } void helloLaoWang() { System.out.println("hello LaoWang"); } }

結果:

構造方法:
Hi,window10
名字:s1 型別:class java.lang.String 值:World!
名字:s2 型別:class java.lang.String 值:java!
名字:s3 型別:class java.lang.String 值:China
方法名:helloChina 方法執行:hello China
方法名:helloJava 方法執行:hello java!
方法名:helloWeekend 方法執行:hello Weekend!
方法名:helloWorld 方法執行:hello World!
方法名:helloLaoWang 方法執行:hello LaoWang