2016-05-16 333 views
6

我有一个必须调用抽象类的私有方法的需求。调用抽象类的私有方法

比方说抽象类看起来象下面这样: -

public abstract class Base { 

    protected abstract String getName(); 

    private String getHi(String v) { 
     return "Hi " + v; 
    } 
} 

能有些让我知道是有办法,我可以叫getHi(可能是通过Reflection或其他方式),这样我可以测试它出来吗?我正在使用Junit 4.12Java 8

我已经经历了这个question但这里的方法在抽象类中不是私有的。

我也经历了这个question即使这个不谈抽象类中的私有方法。

我不是在问这里是否应该测试私有方法,或者测试私有方法的最佳策略是什么。网上有很多关于这方面的资源。我只是想问我们应该如何在java中调用一个抽象类的私有方法。

+0

见http://stackoverflow.com/q/105007/3788176 –

+1

我知道有关的讨论中,我们是否应该测试私有方法还是不行。其实我有兴趣知道是否可以从测试代码中调用抽象类的私有方法? – tuk

+0

请参阅http://stackoverflow.com/questions/6913325/annotation-to-make-a-private-method-public-only-for-test-classes,它提供了一些方法。特别是,[这个答案](http://stackoverflow.com/a/6913775/3788176)链接到关于测试私有方法的JUnit文档。 –

回答

2

我能够调用一个抽象类的私有方法如下: -

比方说,我有扩展抽象基类的类: -

public class Child extends Base { 
    protected String getName() { 
    return "Hello World"; 
    } 
} 

然后我能够调用下面的私有方法: -

Child child = new Child(); 
try { 
     Method method = Base.class.getDeclaredMethod("getHi", String.class); 
     method.setAccessible(true); 
     String output = (String) method.invoke(child, "Tuk"); 
     System.out.println(output); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    }