java 构造一个对象、执行相关静态和对象的方法

 

 

 

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

posted @ 2022-04-22 09:51  蜜铀  阅读(44)  评论(0编辑  收藏  举报