Reflection and constructors with interface argument
I'm trying to modify a private field inside a class, which has a constructor taking interface as an argument. I am having trouble instantiating such a class (it throws java.lang.IllegalArgumentException: wrong number of arguments). Now the code stripped to the most important details is as follows:
Here is my reflection code to inject different boolean value (unique field is true by default I want false there):
private void modifySitePatterns() {
try {
Thread thread = Thread.currentThread();
ClassLoader classLoader = thread.getContextClassLoader();
Class<?> classToModify = Class.forName(
"dr.evolution.alignment.SitePatterns", true, classLoader);
Constructor<?>[] constructors = classToModify
开发者_如何学Python .getDeclaredConstructors();
Field[] fields = classToModify.getDeclaredFields();
Object classObj = constructors[0].newInstance(new Object[] {}); //this throws the exception
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName() == "unique") {
System.out.println(i);
fields[i].setAccessible(true);
fields[i].set(classObj, false);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}// END: modifySitePatterns()
Here is the class I'm trying to modify:
public class SitePatterns implements SiteList, dr.util.XHTMLable {
//omitted
private boolean unique = true;
public SitePatterns(Alignment alignment) {// constructor 0
this(alignment, null, 0, 0, 1);
}
}
And the argument that is giving me trouble:
public interface Alignment extends SequenceList, SiteList {
//omitted
public abstract class Abstract implements Alignment {
}
//omitted
}
How should I proceed with passing a fake argument to the instance of the constructor?
(Probably obvious) You need to pass in an Alignment. If you don't have a non-abstract subclass to instantiate, I think you'll need to make a dummy one.
You currently have no concrete implementation that you have shown us.
//anonymous implementation
Object classObj = constructors[0].newInstance(new Alignment() {
//alignment implementation...
});
//or concrete implementation
Object classObj = constructors[0].newInstance(new AlignmentImpl());
The comment indicating to use getDeclaredConstructors()
is correct, be specific about which one you want since it has (at least) 2 from what your code is showing.
To instantiate your class, you'll need an instance of some class that implements your Alignment
interface. Construct that first, then pass it to the newInstance
method on the constructor.
精彩评论