我想编写一个可以动态接收不同类型对象的方法。一旦我收到动态对象,我就可以根据与该对象关联的属性在方法内部执行某些操作。它会像下面这样:
MainClass{
class1 obj1;//all these are pojo
class2 obj2;
class3 obj3;
method1(<dynamic_object>)
}
method1(<dynamic_object>){
if(dynamic_object.property 1 == true){
callmethod2(dynamic_object.property 1)
}
else{
callmethod3(dynamic_object.property 1)
}
}
这里dynamic_objects是不同类型的。 我怎样才能在Java中实现这一点? 我不想在这里使用反射。
最佳答案
为了识别对象的类型,您可以使用 instanceof运算符(operator)。
private void instanceOfMethodExample(Object object){
if(object instanceof String)
print("Its a String!");
else if(object instanceof Integer)
print("Its an Int!");
else
print("Its a " + object.getClass().getName()); // by calling getClass().getName() method you take the class name of the object as a String
}
关于java - 在同一方法上动态传递不同类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361405/