如何使用反射(Java)调用私有静态方法?

sna*_*ile 58 java reflection invoke

我想调用一个私有静态方法.我有它的名字.我听说可以使用Java反射机制完成它.我该怎么做?

编辑:尝试调用方法时遇到的一个问题是如何指定其参数的类型.我的方法接收一个参数,其类型是Map.因此我做不到Map<User, String>.TYPE(在运行时因为Java类型擦除而没有Map这样的东西).有没有其他方法来获得该方法?

Lan*_*dei 101

假设您要调用MyClass.myMethod(int x);

Method m = MyClass.class.getDeclaredMethod("myMethod", Integer.TYPE);
m.setAccessible(true); //if security settings allow this
Object o = m.invoke(null, 23); //use null if the method is static
Run Code Online (Sandbox Code Playgroud)

  • @snakile:尝试`MyClass.class.getDeclaredMethod("myMethod",Map.class);`为你的情况 (6认同)

Cra*_*lus 9

反射教程调用main

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class InvokeMain {
    public static void main(String... args) {
    try {
        Class<?> c = Class.forName(args[0]);
        Class[] argTypes = new Class[] { String[].class };
        Method main = c.getDeclaredMethod("main", argTypes);
        String[] mainArgs = Arrays.copyOfRange(args, 1, args.length);
        System.out.format("invoking %s.main()%n", c.getName());
        main.invoke(null, (Object)mainArgs);

        // production code should handle these exceptions more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    } catch (NoSuchMethodException x) {
        x.printStackTrace();
    } catch (IllegalAccessException x) {
        x.printStackTrace();
    } catch (InvocationTargetException x) {
        x.printStackTrace();
    }
    }
}
Run Code Online (Sandbox Code Playgroud)