How to access Java Private methods and fields

I left Java for about two weeks, mainly because I wasn't happy with it, but I'm in a hurry for development, so I'm going to test it with JUnit! Even if you try to use a method or field variable whose access modifier is Private, you cannot call it from another class as a matter of course (^ ω ^) ...

But well, I did a lot of research and found out, so I'll make a note of it. If you like, try fertilizing it.

usage environment: OS:Windows 10 java ver:8 IDE:eclipse 4.6 Neon

Download the Jar file

External site (https://ja.osdn.net/projects/sfnet_junit-addons/releases/) Get the junit-addons Jar file from.

Save it in a nice local directory.

Let's add a Jar file

Start eclipse, right-click on [Package Explorer], and add an external Jar from [Build Path]-> [Build Path Configuration]-> [java Build Path].

WS000001.JPG

Now you are ready.

By the way, what is the API specification like?

http://junit-addons.sourceforge.net/junitx/util/PrivateAccessor.html

Hmmmm.

I don't know at all.

Tell me Guguru Sensei!

Move in a mess

Prepare a test program. First of all, from the program to be tested.

Sample.java


public class Sample {

//private field variable
	private int x = 10;

//Private and static field variables
	private static int y = 20;

//private method
	private String testMethod(String x){

		return x;
	}

//private and static methods
	private static String testStaticMethod(String y, String z){

		return y + z;
	}

}

Next, prepare a class file for JUnit.

SampleTest.java


import static org.junit.Assert.*;

import org.junit.Test;

import junitx.util.PrivateAccessor;

public class SampleTest {

	@Test
	/**
	 *Test function to access private fields and methods
	 */
	public void privateGetField() throws Throwable {
		Sample sample = new Sample();

		try {

//A method for accessing private field variables.
//First argument:Instance variable of the class under test Second argument:Field variable name you want to access
			int x = (int)PrivateAccessor.getField(sample, "x");

//Compare measured value and expected value by assertion
			assertEquals(x,10);

//Private and static field variables can be accessed in a similar way. Explanation omitted
			int y = (int)PrivateAccessor.getField(sample, "y");
			assertEquals(y,20);


//A method for accessing a private function.
//First argument:Instance variable of the class under test Second argument:Field function name you want to access
//Third argument:Array of argument types Fourth argument:Array of argument values
			String method_x = (String)PrivateAccessor.invoke(	sample,
																"testMethod",
																new Class[]{String.class},
																new Object[]{"private_x"});
			assertEquals(method_x,"private_x");

//Private and static functions can be accessed in a similar way. Devise the third and fourth arguments according to the number of argument types
			String method_y = (String)PrivateAccessor.invoke(	sample,
																"testStaticMethod",
																new Class[]{String.class,String.class},
																new Object[]{"private_","static_y"});
			assertEquals(method_y,"private_static_y");


		} catch (NoSuchFieldException e) {

			e.printStackTrace();

		}finally{

		}
    }
}

Run

Doya!

2017y02m12d_220044187.jpg

did it!

bonus

You can also set a value to a private field variable.

SampleTest.java



//Omitted on the way

	@Test
	/**
	 *A function that sets a value in a private field variable
	 */
	public void privateSetField(){

		Sample sample = new Sample();

		try {

//First argument: Instance variable of the class under test Second argument: Name of variable
//Third argument:Value you want to set
			PrivateAccessor.setField(sample, "x", 100);

//Check if it was set!
			int get_x = (int)PrivateAccessor.getField(sample, "x");
			assertEquals(get_x,100);

		} catch (NoSuchFieldException e) {

			e.printStackTrace();

		}finally{

		}
	}


The end

Recommended Posts

How to access Java Private methods and fields
How to call classes and methods
How to use class methods [Java]
[Java] How to output and write files!
How to test a private method in Java and partially mock that method
[Java] How to use FileReader class and BufferedReader class
[Java] How to get and output standard input
How to get and study java SE8 Gold
[Java] How to use Calendar class and Date class
[Java] How to omit the private constructor in Lombok
[Java] Types of comments and how to write them
Java memory management and how to read GC Viewer
[Java] Refer to and set private variables with reflection
How to convert A to a and a to A using AND and OR in Java
[Java] How to use Map
How to lower java version
[Java] How to use Map
How to uninstall Java 8 (Mac)
[Java] Generics classes and generics methods
How to use java Optional
How to minimize Java images
How to write java comments
How to use java class
Check Java9 Interface private methods
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java] How to use string.format
How to use Java Map
How to set Java constants
Java methods and method overloads
How to use Java variables
[Java] How to implement multithreading
How to initialize Java array
Java conditional branching: How to create and study switch statements
How to separate words in names in classes, methods, and variables
Difference between Java and JavaScript (how to find the average)
[Rails] Differences between redirect_to and render methods and how to output render methods
What happened in "Java 8 to Java 11" and how to build an environment
How to write and notes when migrating from VB to JAVA
How to develop and register a Sota app in Java
Differences in how to handle strings between Java and Perl
How to use StringBurrer and Arrays.toString.
How to study Java Silver SE 8
How to use Java HttpClient (Get)
About Java static and non-static methods
How to use EventBus3 and ThreadMode
Studying Java # 6 (How to write blocks)
[Java] How to update Java on Windows
How to make a Java container
How to disassemble Java class files
How to use Java HttpClient (Post)
[Java] How to use join method
How to use equality and equality (how to use equals)
[Processing × Java] How to use variables
[Java] How to create a folder
How to connect Heroku and Sequel
How to decompile java class files
[Java] How to use LinkedHashMap class
How to convert LocalDate and Timestamp
[JavaFX] [Java8] How to use GridPane