1

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?

2
  • I'm curious as to why, if every object has this method, that you can't say that every object in the collection implements a given interface, extends a given abstract class, or is a child (either directly or indirectly) of another concrete class. Commented Mar 28, 2011 at 22:18
  • Because I thought there might be an easier way. Commented Mar 28, 2011 at 22:24

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I almost want to +1 this, but I don't think that Reflection is the answer. I really like the paragraph below the link - my guess is that there is a larger design issue here that's causing the problem at hand.
1

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).

Comments

1

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

2 Comments

Yes, but it should work on multiple methods that have that class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.