0

I want a method which returns an Object which is given a class depnding on the value of the String that is passed through

 public static Object createObject(String classname){
    Object myobject = null;
     try {
            Class myclass = Class.forName(classname);
            myobject = myclass.newInstance();
            System.out.println(myobject.objectAttribute);
    }catch(Exception e){
    }
    return myobject;

}

I want to then be able to print out an Attribute (e.g objectAttribute) that i know will be held by all possible classes that classname could represent. The possible classes are defined in separate files. But the compiler gives error cannot find symbol objectAttribute. How can i access an atribute of this object?

sorry for poorly worded question

Thanks for any Help

Drake28
  • 11
  • 1
    If you want to use reflection to work with classes dynamically, perhaps you should **read the documentation** about it: [ The Java™ Tutorials - The Reflection API](https://docs.oracle.com/javase/tutorial/reflect/index.html) – Andreas Sep 23 '17 at 14:09

2 Answers2

0

You can use getFields() method to access all the fields, e.g.:

Class myclass = Class.forName("ClassName");
Field[] fields = myclass.getDeclaredFields();
for(Field field : fields) {
    System.out.println(field.getName());
}
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

As the compiler says, a java.lang.Object doesn't have an objectAttribute field, so you can't access it via an Object reference. If you have some known base class that provides this attribute you could just cast myobject to it:

System.out.println(((BaseClass) myobject).objectAttribute);

Otherwise, you could rely on reflection:

Field field  = myclass.getField("objectAttribute");
System.out.println(field.get(myobject));
Mureinik
  • 297,002
  • 52
  • 306
  • 350