我有一个帮助类,它通过以下方法得到通知
public void setObject(Object obj) {
this.obj = obj
}
obj有getter方法。有没有办法确定调用者关于obj的类型。该对象可以采用任何对象,如:
List<Switch>
Switch
List<Link>
调用者必须在调用getter方法后处理obj。有办法吗?
答案 0 :(得分:0)
您始终可以从obj.getClass()
了解班级(然后是班级名称)。你想进一步做什么?
如果你想在obj上调用方法 - 你需要反思.. 像这样的东西 -
Class myClass = obj.getClass();
Method m = myClass.getDeclaredMethod("get",new Class[] {});
Object result = m.invoke(myObject,null);
答案 1 :(得分: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;
}
}
正如您所看到的,我有一个返回对象类型的方法,如果您要更改该方法的返回值,您可以轻松地了解正在发生的事情。还有一件事您无法在运行时猜测泛型类型,因为“通用类型在运行时被删除”。希望你明白我的意思。欢呼
答案 2 :(得分:0)
这可能会对你有所帮助。它告诉您如何获取参数化类型。