简体   繁体   English

Java方法对类型对象的调用

[英]Java method call on type object

I want to have a method that takes an Object as a parameter, and add it to an arraylist. 我想有一个将Object作为参数的方法,并将其添加到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. 稍后,我想在此对象上调用方法,但是在空洞的时间里,我不想将对象定义为特定类型,只需键入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? 有什么办法可以强迫它调用该方法?

Cast it: 投放:

((YourObject)element.get(i)).someMethodYouKnowItHas()

Another alternative is to have your underlaying collection as a generic type: 另一种选择是将底层集合作为通用类型:

class YourClass {
    List<YourObject> elementList = new ArrayList<YourObject>();

...
    public void addElement( Object obj ) {
       elementList.add( ( YourObject ) obj );
    }

    public void someWhereElse() {
       elementList.get(i).operationOne();
       elementList.get(i).operationTwo();
       elementList.get(i).operationThree();
    }
...
}

Not sure if it makes sense in your case though 不确定是否适合您的情况

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/ 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. 您“知道它具有”某某方法的事实告诉我,它应该实现一个告诉编译器它具有该方法的接口。

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. 您可能知道以下事实:您向ArrayList添加了某种类型的对象,并且该对象位于特定的索引处。 However, Java doesn't. 但是,Java没有。 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). 您需要指定ArrayList中的所有内容均为特定类型(或扩展特定的calss或实现特定的接口),或者需要将对象强制转换为您知道的类型(并确保任何事情都不会中断,请处理不符合您期望的情况)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM