How do I invoke a private static method using reflection (Java)?

前端 未结 5 445
[愿得一人]
[愿得一人] 2020-11-29 03:32

I would like to invoke a private static method. I have its name. I\'ve heard it can be done using Java reflection mechanism. How can I do it?

EDIT:

5条回答
  •  伪装坚强ぢ
    2020-11-29 04:04

    Invoke main from reflection tutorial

    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();
        }
        }
    }
    

提交回复
热议问题