How to pass ConstructorArgs type variable to a method as a parameter

77 Views Asked by At

I'm trying to use easymock library's createMock method. The method definition looks like this:

createMock(Class<T> var1, ConstructorArgs var2, Method... var3); 

(https://easymock.org/api/org/easymock/IMocksControl.html) I want to use a particular constructor from my class and hence need to pass constructor argument with initial arguments. ConstructorArgs definition:

ConstructorArgs(Constructor<?> constructor, Object... initArgs) 

(https://easymock.org/api/org/easymock/ConstructorArgs.html) Can someone please help with how to initialize constructorArgs with the constructor that

I need to use and the initial values that I need to pass to the the constructor?

1

There are 1 best solutions below

0
Kyle On

To get the Constructor object of a class you'll have to use reflection.

Here's an example:

import java.lang.reflect.Constructor;

public class HelloWorld {
    public static void main(String []args){
        try {
            Class[] argumentsOfConstructor = new Class[] { String.class }; // Arguments of the constructor I wish to get
            Constructor constructor = HelloWorld.class.getConstructor(argumentsOfConstructor); // Call getConstructor on class type
         
            System.out.println(constructor);
        } catch (Exception ex) { }
    }
    
    public HelloWorld(String test) {
        // Example constructor
    }
}

Since ConstructorArgs accepts initArgs as a vararg of Objects, you should be able to pass the respective arguments that you would normally pass into the constructor while instantiating it.

From my example above, it would be:

Class[] argumentsOfConstructor = new Class[] { String.class };
Constructor constructor = HelloWorld.class.getConstructor(argumentsOfConstructor);

ConstructorArgs constructorArgs = new ConstructorArgs(constructor, "my string");