Java 类型对象上的方法调用
我想要一个以对象作为参数的方法,并将其添加到数组列表中。后来,我想调用这个对象的方法,但是空洞的时候,我不想将对象定义为特定类型,只是类型为Object。我知道该对象包含我想要调用的方法,因为我确保只使用该方法传递对象。像这样的事情:
public void addElement(Object obj){
elementlist.add(obj);
}
.
.
.
elementlist.get(i).SomeMethodIknowItHas();
但是,这不起作用。有什么方法可以强制它调用该方法吗?
I want to have a method that takes an Object as a parameter, and add it to an arraylist. Later on, i want to call a method on this object, but the hole time, I don not want to define the object as a specific type, just type Object. I know the object contains the method I want to call because I make sure I only pass object with that method. Something like this:
public void addElement(Object obj){
elementlist.add(obj);
}
.
.
.
elementlist.get(i).SomeMethodIknowItHas();
However, this is not working. Is there some way I can force it to call that method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您确实不想将对象强制转换为特定类型,则必须使用反射。
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
但是,这通常被认为是不好的做法,您应该看看是否有某种方法可以将泛型与接口或基类一起使用。您“知道它有”这样那样的方法这一事实告诉我,它应该实现一个接口,告诉编译器它有该方法。
If you really don't want to cast the object as a specific type, you will have to use reflection.
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
However, this is generally considered bad practice, and you should see if there is some way you can use generics with interfaces or base classes instead. The fact that you "know it has" such-and-such method tells me that it ought to implement an interface that tells the compiler it has that method.
您可能知道您向 ArrayList 添加了某种类型的对象,并且它位于特定的索引处。然而,Java 却没有。您需要指定 ArrayList 中的所有内容都是特定类型(或扩展特定类,或实现特定接口),或者需要将对象强制转换为您知道的类型(并且还要确保没有任何事情会发生,当情况不是你期望的那样时处理它)。
You might know for a fact that you added an object of a certain type to the ArrayList and it's at a particular index. However, Java doesn't. You need to either specify that everything in the ArrayList is of a particular type (or extends a specific calss, or implements a particular interface) or you need to cast the object to the type that you know it is (and also, to ensure that nothing ever breaks, deal with the case when it isn't what you expect it to be).
投射它:
另一种选择是将您的底层集合作为通用类型:
但不确定它对您的情况是否有意义
Cast it:
Another alternative is to have your underlaying collection as a generic type:
Not sure if it makes sense in your case though