Никогда бы не подумал что это частый вопрос, но тем не менее 
Цитата:
Сообщение от mutagen
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
| import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class LoadAndRun {
public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException,
IllegalAccessException {
String fileName = "MyClass.java";
String className = "MyClass.class";
File[] f = new File[] { new File(fileName), new File(className) };
for (File file : f)
file.delete();
BufferedWriter fos = new BufferedWriter(new FileWriter(fileName));
fos.write("public class MyClass { public String toString() { return \"MyClass running\"; } }");
fos.flush();
fos.close();
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = javac.getStandardFileManager(null, null, null);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(Arrays
.asList(new File[] { new File(fileName) }));
javac.getTask(null, fileManager, diagnostics, null, null, compilationUnits1).call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics())
System.out.println(diagnostic);
fileManager.close();
MyClassLoader loader = new MyClassLoader();
Class my = loader.getClassFromFile(new File(className));
Object o = my.newInstance();
System.out.println(o.toString());
}
static class MyClassLoader extends ClassLoader {
public Class getClassFromFile(File f) {
byte[] raw = new byte[(int) f.length()];
//System.out.println(f.length());
InputStream in = null;
try {
in = new FileInputStream(f);
in.read(raw);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return defineClass(null, raw, 0, raw.length);
}
}
} |
|
Добавлено через 3 часа 42 минуты
и ещё один вариант
Java | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class CompileSourceInMemory {
public static void main(String args[]) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
out.println("public class HelloWorld {");
out.println(" public static void main(String args[]) {");
out.println(" System.out.println(\"This is in another java file\");");
out.println(" }");
out.println("}");
out.flush();
out.close();
JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());
System.out.println(file);
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
boolean success = task.call();
for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics())
System.out.println(diagnostic);
System.out.println("Success: " + success);
if (success) {
try {
MyClassLoader loader = new MyClassLoader();
Class my = loader.getClassFromFile(new File("HelloWorld.class"));
Method m = my.getMethod("main", new Class[] { String[].class });
Object o = my.newInstance();
m.invoke(o, new Object[] { new String[0] });
} catch (Exception e) {
e.printStackTrace();
}
}
}
static class JavaSourceFromString extends SimpleJavaFileObject {
final String code;
JavaSourceFromString(String name, String code) {
super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.code = code;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return code;
}
}
static class MyClassLoader extends ClassLoader {
public Class getClassFromFile(File f) {
byte[] raw = new byte[(int) f.length()];
System.out.println(f.length());
InputStream in = null;
try {
in = new FileInputStream(f);
in.read(raw);
} catch (Exception e) {
e.printStackTrace();
}
try {
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return defineClass(null, raw, 0, raw.length);
}
}
} |
|
|