0

I created a java class file Dynamically by passing data type and field name to my method. Now I want to pass the same values Dynamically (from Console) how can I do.

Below is My Code:

public class MapFirst {
public static void createClass(String className,
        Map<Class<?>, String> fields) throws IOException {
    StringBuilder builder = new StringBuilder();

    String packageName;
    int idx = className.lastIndexOf('.');
    if (idx >= 0) {
        packageName = className.substring(0, idx);
        className = className.substring(idx + 1);
    } else
        packageName = null;

    if (packageName != null)
        builder.append("package ").append(packageName).append(";\n");

    builder.append("\n");

    builder.append("public class ").append(className).append("\n");

    builder.append("{\n");

    boolean flag = false;
    for (Map.Entry<Class<?>, String> field : fields.entrySet()) {
        Class<?> type = field.getKey();
        String name = field.getValue();
        String nameCapitalized = Character.toUpperCase(name.charAt(0))
                + name.substring(1);

        if (flag)
            builder.append("\n");
        flag = true;
        builder.append("    private ").append(type).append(" ")
                .append(name).append(";\n");
        builder.append("\n");
        builder.append("    public ").append(type).append(" get")
                .append(nameCapitalized).append(" ()\n");
        builder.append("    {\n");
        builder.append("        return ").append(name).append(";\n");
        builder.append("    }\n");
        builder.append("\n");
        builder.append("    public void set").append(nameCapitalized)
                .append(" (").append(type).append(" ").append(name)
                .append(")\n");
        builder.append("    {\n");
        builder.append("        this.").append(name).append(" = ")
                .append(name).append(";\n");
        builder.append("    }\n");
    }

    builder.append("}\n");

    File dir = new File(packageName.replaceAll("\\.",
            Matcher.quoteReplacement(System.getProperty("file.separator"))));

    dir.mkdirs();

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(new File(dir, className + ".java"))));

    writer.write(builder.toString());
    writer.close();
}

public static void main(String[] args) throws Exception {
    Map<Class<?>, String> fields = new HashMap<Class<?>, String>();
    fields.put(int.class, "foo");
    fields.put(double.class, "bar"); // I wnat to pass these values from console
    fields.put(char.class, "me");
    fields.put(int.class, "i");
    createClass("my.pkg.MyClass1", fields);
}
}

Now I want pass those values Dynamically how Can I do.

1
  • Can I ask why you are doing this? As much as I hate them, a Map might be a better option here. Commented Feb 11, 2014 at 17:46

2 Answers 2

2

Since the class is not known at compile time the only way to access it is by reflection.

I don't know how you have written createClass but if you manage to create a class that extends another class known at compile time then you can use polymorphism to access its methods without reflection.

Sign up to request clarification or add additional context in comments.

5 Comments

I am afraid I am unable to understand your question due to language issues. Can you please update your question with sample code of what you would like to do?
sure @Miserable Variable
So createClass just creates a source file. How does it get compiled? You will need to run javac on it, and ensure that the generated .class file is in classpath. Irrespective of that, I don't see how you can access its members without reflection.
So there is no way to create a java class without reflection
So far you have not even created a class, you have only written a source file.
0

This is the one exception where I would advise to revert to JavaScript or BeanShell (java like scripting) or so. Interoperation with java can be done with the Java Scripting API.

However maybe javassist (AOP/byte code) may be what you are searching for, though complex.

1 Comment

thank you @Joop Eggen I got the result, But instead of passing field type (int.class,..) I want to read from console that's i want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.