Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.lang.reflect.InvocationTargetException;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.net.URLClassLoader;
- import java.nio.charset.StandardCharsets;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.TreeMap;
- import java.util.UUID;
- public class JavaCodeGenerator {
- private static List<String> generateSource(String className, Map<String, String> fields, Map<String, List<String>> methods)
- throws IllegalArgumentException {
- if (!validName(className)) { throw new IllegalArgumentException("className"); }
- if (fields == null) { throw new IllegalArgumentException("fields"); }
- if (methods == null) { throw new IllegalArgumentException("methods"); }
- final List<String> source = new ArrayList<>();
- source.add(String.format("public class %s {", className));
- for (Map.Entry<String, String> entry : fields.entrySet()) {
- if (!validName(entry.getKey())) { throw new IllegalArgumentException("fields"); }
- source.add("");
- source.add(String.format(" public %s %s;", entry.getValue(), entry.getKey()));
- }
- for (Map.Entry<String, List<String>> entry : methods.entrySet()) {
- if (!validName(entry.getKey())) { throw new IllegalArgumentException("methods"); }
- source.add("");
- source.add(String.format(" public void %s() {", entry.getKey()));
- for (String statement : entry.getValue()) {
- final String trimStatement = statement.trim();
- if (statement.startsWith("PRINT")) {
- final String value = statement.substring("PRINT".length()).trim();
- if (!value.startsWith("#")) {
- if (validName(value)) {
- if (fields.get(value) != null) {
- source.add(String.format(" System.out.println(%s);", value));
- } else {
- throw new IllegalArgumentException("methods");
- }
- } else if (validString(value) || validNumber(value)) {
- source.add(String.format(" System.out.println(%s);", value));
- } else {
- throw new IllegalArgumentException("methods");
- }
- }
- }
- }
- source.add(" }");
- }
- source.add("}");
- return source;
- }
- private static String buildClassFile(String className, List<String> source, String path)
- throws IllegalArgumentException, IOException, InterruptedException {
- if (!validName(className)) { throw new IllegalArgumentException("className"); }
- if (source == null || source.isEmpty()) { throw new IllegalArgumentException("source"); }
- if (path == null || path.isEmpty()) { throw new IllegalArgumentException("path"); }
- final File directory = new File(path, UUID.randomUUID().toString());
- directory.mkdir();
- final File sourceFile = new File(directory, className + ".java");
- try (
- FileOutputStream fos = new FileOutputStream(sourceFile);
- OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
- BufferedWriter bw = new BufferedWriter(osw)
- ) {
- for (String line : source) {
- bw.write(line);
- bw.newLine();
- }
- } catch (IOException ex) {
- throw ex;
- }
- if (sourceFile.exists()) {
- final String fs = System.getProperty("file.separator");
- final Process process = new ProcessBuilder(
- System.getenv("JAVA_HOME") + fs + "bin" + fs + "javac",
- "-source",
- "8",
- "-target",
- "8",
- "-encoding",
- "utf8",
- "-cp",
- directory.getAbsolutePath(),
- "-d",
- directory.getAbsolutePath(),
- sourceFile.getAbsolutePath()
- ).start();
- final int exitCode = process.waitFor();
- sourceFile.delete();
- if (exitCode != 0) {
- final File classFile = new File(directory, className + ".class");
- if (classFile.exists()) {
- classFile.delete();
- }
- directory.delete();
- return "";
- }
- }
- return directory.getAbsolutePath();
- }
- private static boolean validName(String name) {
- if (name == null || name.isEmpty()) return false;
- final char[] chars = name.toCharArray();
- if (chars[0] != '_' && !Character.isLetter(chars[0])) return false;
- for (int i = 1; i < chars.length; i++) {
- if (chars[i] != '_' && !Character.isLetter(chars[i]) && !Character.isDigit(chars[i])) return false;
- }
- return true;
- }
- private static boolean validString(String str) {
- if (str == null || str.isEmpty()) return false;
- final char[] chars = str.toCharArray();
- if (chars.length < 2) return false;
- if (chars[0] != '\"') return false;
- if (chars[chars.length - 1] != '\"') return false;
- for (int i = 1; i < chars.length - 1; i++) {
- if (chars[i] == '\"') return false;
- }
- return true;
- }
- private static boolean validNumber(String number) {
- if (number == null || number.isEmpty()) return false;
- final char[] chars = number.toCharArray();
- for (int i = 0; i < chars.length; i++) {
- if (!Character.isDigit(chars[i])) return false;
- }
- return true;
- }
- private static int parseNumber(String number) {
- try {
- return Integer.parseInt(number);
- } catch (NumberFormatException ex) {
- return 0;
- }
- }
- private static void usingClass(String className, String path)
- throws ClassNotFoundException, MalformedURLException,
- IllegalAccessException, NoSuchFieldException, InstantiationException,
- NoSuchMethodException, InvocationTargetException {
- final URL[] urls = { new File(path).toURI().toURL() };
- final URLClassLoader classLoader = new URLClassLoader(urls);
- final Class userClass = classLoader.loadClass(className);
- final Field id = userClass.getField("id");
- final Field name = userClass.getField("name");
- final Field password = userClass.getField("password");
- final Method printHello = userClass.getMethod("printHello");
- final Object user = userClass.newInstance();
- id.set(user, Integer.valueOf(1013));
- name.set(user, "FoxMulder");
- password.set(user, "trustno1");
- dumpObject(user);
- printHello.invoke(user);
- }
- private static void dumpObject(Object object)
- throws IllegalAccessException, NoSuchFieldException {
- final Field[] fields = object.getClass().getDeclaredFields();
- final Map<String, String> sortedFields = new TreeMap<>();
- for (Field field : fields) {
- final String name = field.getName();
- final Object value = field.get(object);
- sortedFields.put(name, value != null ? value.toString() : "");
- }
- final String className = object.getClass().getCanonicalName();
- System.out.println(String.format("<%s>", className));
- for (Map.Entry<String, String> entry : sortedFields.entrySet()) {
- final String name = entry.getKey();
- final String value = entry.getValue();
- System.out.println(String.format(" <%s>%s</%s>", name, replaceSpecialXmlChars(value), name));
- }
- System.out.println(String.format("</%s>", className));
- }
- private static String replaceSpecialXmlChars(String str) {
- if (str == null || str.isEmpty()) return str;
- return str.replace("&", "&").replace("<", "<").replace(">", ">");
- }
- public static void main(String[] args) {
- try {
- final Map<String, String> fields = new HashMap<>();
- fields.put("id", "Integer");
- fields.put("name", "String");
- fields.put("password", "String");
- final Map<String, List<String>> methods = new HashMap<>();
- final List<String> methodCode = new ArrayList<>();
- methodCode.add("PRINT \"Password is:\"");
- methodCode.add("PRINT password");
- methods.put("printHello", methodCode);
- System.out.println("SUB printHello()");
- for (String line : methodCode) {
- System.out.println(line);
- }
- System.out.println("END SUB");
- final List<String> source = generateSource("User", fields, methods);
- final String path = buildClassFile("User", source, System.getProperty("user.dir"));
- if (!path.isEmpty() && (new File(path, "User.class")).exists()) {
- System.out.println("Class User created in: " + path);
- try {
- usingClass("User", path);
- } catch (Exception ex) {
- System.err.println("[ERROR] " + ex.getClass().getName() + ' ' + ex.getMessage());
- } finally {
- (new File(path, "User.class")).delete();
- (new File(path)).delete();
- }
- }
- } catch (Exception ex) {
- System.err.println("[ERROR] " + ex.getClass().getName() + ' ' + ex.getMessage());
- }
- }
- }
Add Comment
Please, Sign In to add comment