如何识别返回对象的方法类型?



>我有一个帮助程序类,它通过以下方法收到通知

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

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

List<Switch>
Switch
List<Link>
调用

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

您始终可以从obj.getClass()中知道类(然后是类名)。你想用它进一步做什么?

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

Class myClass = obj.getClass();
Method m = myClass.getDeclaredMethod("get",new Class[] {});
Object result = m.invoke(myObject,null);
您可以使用

运算符知道对象类型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;
    }
}

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

这可能会对您有所帮助。它告知您如何获取参数化类型。

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

最新更新