2017-04-12 136 views
1

我想调用使用反射的方法。使用反射的Java调用方法

我调用的方法不是静态的,而是在我调用它的同一个类中。

的简化版本我的代码:

public class Test { 
    public static void main(String[] args) { 
    Test instance = new Test(); 
    if (args.length > 0) { 
     instance.doWork(args[0]); 
    } 
    } 

    private void doWork(String methodName) { 
    Method method; 

    try { 
     method = this.getClass().getMethod(methodName); 
     method.invoke(this); 
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { 
     [...] 
    } 
    } 

    private void MethodOne() { ... }; 
    private void MethodTwo() { ... }; 
    [...] 
    private void MethodTwenty() { ... }; 
} 

我所得到的是一个java.lang.NoSuchMethodException: correct.package.and.class.MethodTwo()尽管包/类/方法存在。

谁能告诉我什么,我做错了什么?

+0

什么是'ARG [0]'?尝试打印出来。 – Sweeper

回答

2

我所得到的是一个java.lang.NoSuchMethodException: correct.package.and.class.MethodTwo()...

您正在调用哪一个是不给回了getMethod()私有方法

假设ARG [0]有方法的正确名称(如果不是你会再次得到java.lang.NoSuchMethodException),2东西必须在这里完成:

  1. 你需要使用getDeclaredMethod(因为MethodOne是私有声明)

  2. 您需要设置的标志访问它.setAccessible(true)(这将让你调用一个被声明为private的方法)

实施例:

Method method; 
    try { 
     method = f.getClass().getDeclaredMethod("doThis"); 

     method.setAccessible(true); 
     method.invoke(f); 
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException 
      | InvocationTargetException e) { 
     System.err.println("Opala, somethign went wrong here!"); 
    } 
+0

谢谢,这工作! –

+0

不用客气@JacobS –

1

您访问方法的方式正确。 方法访问说明符是私有的。因此它是抛出错误。

请将访问说明符更改为公开,它将工作。

import java.lang.reflect.Method; 

public class Test { 
    public static void main(String[] args) { 
    Test instance = new Test(); 
    if (args.length > 0) { 
     instance.doWork(args[0]); 
    } 
    } 

    private void doWork(String methodName) { 
    Method method; 

    try { 
     method = this.getClass().getMethod(methodName); 
     method.invoke(this); 
    } catch (Exception e) { 

    } 
    } 

    public void MethodOne() { System.out.println("Method 1"); }; 
    public void MethodTwo() { System.out.println("Method 2"); }; 
    public void MethodTwenty() { System.out.println("Method 3"); }; 
} 

如果您尝试访问私有方法或构造函数,则需要更改代码。

感谢, Thiruppathi小号

+0

我也试过这种方式,效果很好。我已经接受了公认的答案,因为它并不强迫我将方法设置为public。 –