java 構造一個物件、執行相關靜態和物件的方法
阿新 • • 發佈:2022-04-22
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class MethodTest { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {// 獲取class類 Class<?> clzz = MethodTest.class; // 獲取類靜態方法 Method m_static = clzz.getMethod("fStatic"); // 執行靜態方法 m_static.invoke(null); // 獲取類的構造器 Constructor<?> constructor = clzz.getConstructor(); // 構造class物件 Object o = constructor.newInstance();// 獲取類的方法 Method m = clzz.getMethod("f"); // 執行類方法 m.invoke(o); } public MethodTest() { System.out.println("constructor called"); } public static void fStatic(){ System.out.println("static method 'fStatic()' called"); } public void f(){ System.out.println("method 'f()' called"); } }
執行結果;
static method 'fStatic()' called
constructor called
method 'f()' called