I do need to use reflections and it mostly works fine. I now just have a prolem, as I don't know how I could do this. This is what it would look lik.
Private Consumer<String> messageUpdate;
public void setMessageUpdate(Consumer<String> messageUpdate)
{
this.messageUpdate = messageUpdate;
}
public void test(String className)
{
Class cls = Class.forName("package." + className);
// Ofcourse the constructor is not empty normally
Constructor<Class> constructorStr = cls.getConstructor();
Object obj = constructorStr.newInstance();
Class[] params = new Class[1];
params[0] = Consumer.class; // Here I don't know what I need
Method method = cls.getDeclaredMethod("setMessageUpdate", params);
method.invoke(obj, messageUpdate); // Here I don't know what I need
}
Without reflection I would do this:
testClass tc = new testClass();
tc.setMessageUpdate(messageUpdate::accept);
// or
tc.setMessageUpdate(new Consumer<String>() {
@Override
public void accept(String s) {
messageUpdate.accept(s);
}
});
Does anybody know the answer?
Aucun commentaire:
Enregistrer un commentaire