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.

有帮助吗?

解决方案

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); 

    }
}

其他提示

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).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top