Java variable type from string

this is my code

Class<?> clazz;
    try {
        clazz = Class.forName("classes.Pizza");
        Object p2 = clazz.newInstance();
        System.out.println(p2.test);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

      

Error: "test cannot be resolved or is not a field" I want to get a string containing the class name and create an object with that type .. something like

String x = "Pizza"
x pizza1 = new x();

      

How should I do it?

+3


source to share


1 answer


You need to overlay an object on a Pizza object:
This can throw a ClassCastException as well:

Class<?> clazz;
try {
    clazz = Class.forName("classes.Pizza");
    Object p2 = clazz.newInstance();
    System.out.println(((Pizza)p2).test);
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (ClassCastException e) {
    e.printStackTrace();
}

      

EDIT: You can't access a field test

when you don't know about it. This way you can access the field:



Class<?> clazz;
try {
    clazz = Class.forName("classes.Pizza");
    Object p2 = clazz.newInstance();
    /*System.out.println(((Pizza)p2).test);*/
    System.out.println(clazz.getDeclaredField("test").get(p2));
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (NoSuchFieldException e) {
    e.printStackTrace();
}

      

Only javadoc written, not checked (and in this case not sure about the exception)

+2


source







All Articles