Answer the question
In order to leave comments, you need to log in
How to serialize in Java 7, or rather save the byte code of functions with the possibility of further loading?
I apologize in advance for the long sections of code and I will be grateful to anyone who will review them.
Source
import java.io.*;
import java.util.ArrayList;
public class ListOfFunc implements Serializable{
interface Executable extends Serializable { void execute(); }
ArrayList<Executable> alFunc = new ArrayList<>();
private static Executable exec1 =new Executable() {
@Override
public void execute() { System.out.println("exec func1"); }
};
private static Executable exec2 =new Executable() {
@Override
public void execute() { System.out.println("exec func2"); }
};
public static void main(String[] args) throws IOException, ClassNotFoundException {
ListOfFunc lf1 =new ListOfFunc();
lf1.alFunc.add(exec1);
lf1.alFunc.add(exec2);
lf1.alFunc.get(0).execute();
lf1.alFunc.get(1).execute();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data1.dat"));
oos.writeObject(lf1);
oos.close();
System.out.println("after loading:");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data1.dat"));
ListOfFunc ex2 = (ListOfFunc) ois.readObject();
ois.close();
ex2.alFunc.get(0).execute();
ex2.alFunc.get(1).execute();
}
}
exec func1
exec func2
after loading:
exec func1
exec func2
import java.io.*;
import java.util.ArrayList;
public class ListOfFunc implements Serializable{
interface Executable extends Serializable { void execute(); }
ArrayList<Executable> alFunc = new ArrayList<>();
public static void main(String[] args) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data1.dat"));
ListOfFunc ex2 = (ListOfFunc) ois.readObject();
ois.close();
// Запустить подряд все загруженные функции
for (int i = 0; i < ex2.alFunc.size(); i++) ex2.alFunc.get(i).execute();
}
}
Answer the question
In order to leave comments, you need to log in
As far as I know, this cannot be done. Here it is described in detail what happens and what happens during serialization: https://habrahabr.ru/post/60317/ Briefly: the method bytecode is not written there.
But, it seems to me, your task can be solved without serialization. Create a jar with these classes, then load it dynamically. stackoverflow.com/questions/11016092/how-to-load-c...
You can compile the class and save the byte code (as a file, into a database, etc.). (Serialization has nothing to do with it). And then dynamically load and execute the byte code.
You can also read about rule sets, which seems to be what you need (but I can’t say more because I don’t know it personally).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question