Zhukov Maxim edited this page Jul 27, 2017 · 3 revisions

While all libraries for testing Private methods in Java basically wrap the Reflection API, Dp4j instead analyzes your code and automatically generates the Reflection API code for you. All you have to do is add dp4j.jar to your CLASSPATH; then just write code as if private methods were not private!

Dp4j.jar contains Annotation Processors that when added to the CLASSPATH of your Java project, they will look for the methods in your code that are annotated with @Test JUnit annotation. Dp4j will then analyze the code of those methods, and if it finds that you are illegally accessing private methods, it will replace your invalid private method reference with equivalent code that uses Java's Reflection API. Once done with that, your code will compile and run successfully, because your invalid calls to Private methods have been replaced with the correct reflection code to legally invoke those private methods from within your @Test annotated method.


To test all of this in action, use the following Unix command to download and run the TESTDRIVE script described below:

wget https://github.com/gk2go/dp4j/releases/download/dp4j-1.2/TESTDRIVE ; chmod +x TESTDRIVE ; ./TESTDRIVE


The TESTDRIVE script below (download using command above) is a Unix script that will:

  1. Download dp4j.jar from the internet to your computer.
  2. Create a sample Java test file (Test10.java) that illegally attempts to access private methods in another class.
  3. Successfully compile Test10.java with the downloaded dp4j.jar in the CLASSPATH (you must have Java's JDK installed).

Please note, below is an incomplete edition of the TESTDRIVE script, abbreviated for presentation clarity. To download the full script use the Unix command above, or view it here.

curl -D log -O --fail -L http://downloads.sourceforge.net/project/dp4j/$v/$jar_file
curl -D log -O --fail -L http://downloads.sourceforge.net/project/dp4j/$v/$md5_file
openssl md5 < $jar_file >> $md5_local
grep -f $md5_local $md5_file

# Start
cat > $test_file << __EOF__
class T10 {
    private static void p(int i, Double d, String... s){}
public class Test10{
    public void t() {
  T10.p(1,new Double(2),"hello", "reflection");

cat $test_file
javac -Averbose=true -cp $jar_file $test_file
echo "When JUnit/TestNG.jar is in the classpath you may use @Test in lieu of @Reflect."