Reputation: 657
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?
Upvotes: 1
Views: 192
Reputation: 199244
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
Upvotes: 1
Reputation: 116187
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).
Upvotes: 1
Reputation: 156564
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.
Upvotes: 1