Question

I have a lots of classes for example this one:

public class DepartmentST {
    public Long id = null;
    public String name = null;
    public String comments = null;
    public Long[] profiles = null;
    public Boolean default_val = false;
}

In main class I create objects of those classes and sent it to general method for example:

DepartmentST mydepartment = new DepartmentST();
generalMethod(mydepartment);

In general Method I want to access to object fields (this my question how?)

public generalMethod(Object myObj) {
    Field[] fields = myObj.getClass().getFields();
    for(Field field : fields) {
        String fieldName = field.getName();
        // I want to access that field how can i tell myObj.fielName ?
    }
}

I'm new in Java I don't know it's stupid question or not.

thanks for any help in advance.

Was it helpful?

Solution

see http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html#get(java.lang.Object)

public generalMethod(Object myObj) {
    Field[] fields = myObj.getClass().getFields();
    for(Field field : fields) {
        String fieldName = field.getName();
        // I want to access that field how can i tell myObj.fielName ?

        Class c = field.getType();
        if (c instanceOf Integer) {
            Integer value = field.getInt (myObj);
        }

        // or

        Object value = field.get (myObj); 

    }
}

OTHER TIPS

You need to "cast" the object to a DepartmentST object:

if (myObj instanceof DepartmentST) {
    DepartmentST department = (DepartmentST) myObj;
    // continue with code

Then use that object instead of myObj.

Basically this code breaks the encapsulation. You need private fields, and you access them through getters and setters. Reflection is another way to go (depending on the context).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top