Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java variable type from string

Tags:

java

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 is "test cannot be resolved or is not a field" I want to get a string containing the class name and create a object with that type.. something like

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

How do i do that ?

like image 575
John Avatar asked Sep 23 '26 22:09

John


1 Answers

You have to cast Object to Pizza object:
This could cause ClassCastException too:

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 cant access the field test, when you dont know about it. So 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();
}

Writed by javadoc only, not tested (and not sure about exception in this case)

like image 77
maskacovnik Avatar answered Sep 25 '26 13:09

maskacovnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!