I'm trying to write a Serializable lambda which can call a method within the object instance which runs it.
I'm going to be passing this lambda to the object instance which is will run it, immediately after instantiating it, but because I want to serialize these objects containing the lambdas, I need a way of dynamically determining a reference to the object instance.
here is what I'd like to do if the currentClass() method existed.
Runnable r = (Runnable & Serializable)() -> {
try {
// currentClass() doesn't exist
Class curClass = Thread.currentThread().currentClass();
Method setCol = curClass.getMethod("setColor", Class.forName("Color"));
setCol.invoke(curClass, Color.BLACK);
} catch (NoSuchMethodException e | ClassNotFoundException e
| IllegalAccessException e | IllegalArgumentException e
| InvocationTargetException e) {
e.printStackTrace();
}
}
MySquare sq = new MySquare();
sq.setRunnable(r);
sq.runRunnable(); // calls r.run()
To clarify, I'd like to serialize sq
. Then when I read recreate sq
from the .ser file, I'd like to be able to execute sq.runRunnable()
Aucun commentaire:
Enregistrer un commentaire