-1

我有一个助手类,它通过以下方法得到通知

public void setObject(Object obj) {
    this.obj =  obj
}

obj 有 getter 方法。有什么方法可以识别调用者关于 obj 的类型。该对象可以采用任何对象,例如:

List<Switch>
Switch
List<Link>

调用者必须在调用 getter 方法后处理 obj。有没有办法做到这一点?

4

3 回答 3

0

这可能会帮助你。它告诉您如何获取参数化类型。

获取 java.util.List 的泛型类型

于 2013-01-24T12:26:28.410 回答
0

您可以使用运算符知道对象类型。instanceof考虑以下示例:

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        if (getObject() instanceof A) {
            System.out.println("A class");
        }
        if (getObject() instanceof B) {
            System.out.println("B class");
        }
        if (getObject() instanceof List) {
            System.out.println("List class");
        }
    }

    /**
     * 
     * @return Object type. 
     */
    public static Object getObject() {
        //Change this value to new A() or new B();
        return new ArrayList<A>();
    }
}
class A {

    private String aName;

    public A(String aName) {
        this.aName = aName;
    }

    public String getaName() {
        return aName;
    }

    public void setaName(String aName) {
        this.aName = aName;
    }
}

class B {

    private String bName;

    public B(String bName) {
        this.bName = bName;
    }

    public String getbName() {
        return bName;
    }

    public void setbName(String bName) {
        this.bName = bName;
    }
}

如您所见,我有一个返回对象类型的方法,如果您要更改该方法的返回值,您可以轻松理解发生了什么。还有一件事您无法在运行时猜测泛型类型,因为“泛型类型在运行前被删除”。希望你明白我的意思。干杯

于 2013-01-24T12:25:25.323 回答
0

您总是可以从obj.getClass(). 你想进一步用它做什么?

如果你想在 obj 上调用方法 - 你需要反射.. 像这样的东西 -

Class myClass = obj.getClass();
Method m = myClass.getDeclaredMethod("get",new Class[] {});
Object result = m.invoke(myObject,null);
于 2013-01-24T12:12:35.237 回答