Reputation: 1123
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 ?
Upvotes: 3
Views: 84
Reputation: 3084
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)
Upvotes: 2