Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a method of a generic type object?

Tags:

java

generics

The below code gives me the error:

SceneNode.java:17: cannot find symbol
symbol  : method execute() location:
class java.lang.Object
                operation.execute();
                         ^ 1 error

Code:

import java.util.LinkedList;
import java.util.Iterator;

public class SceneNode<T>{
    T operation;    
    public SceneNode() {
    }   
    public SceneNode(T operation) {
        this.operation = operation;
    }
    public void setOperation(T operation) {
        this.operation = operation;
    }
    public void doOperation() {
        operation.execute();
    }
}

It's a cut down (for your readability) start of a simple scene graph. The node could be a model, transformation, switch, etc., so I made a variable called operation that's type is defined by the T class variables. This way I can pass a Transformation / Model / Switch object (that has an execute method) and pass it like this:

SceneNode<Transformation> = new SceneNode<Transformation>(myTransformation);

I'm pretty sure having a base class of SceneNode and subclassing for all the various types of nodes would be a better idea (I was trying out generics, only learnt about them recently). Why doesn't this work? I must be missing something fundamental about generics.

like image 685
Callum Avatar asked Feb 26 '11 20:02

Callum


People also ask

How do you declare a generic method in Java?

When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char. Test<int> obj = new Test<int>(20);

How do you declare a generic method How do you invoke a generic method?

Generic MethodsAll generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.


1 Answers

Recently I came across a situation where I had to call a method on generic object. Getting reflection in action worked for me.

public class SceneNode<T>{
    T operation;    
    public SceneNode() {
    }   
    public SceneNode(T operation) {
        this.operation = operation;
    }
    public void setOperation(T operation) {
        this.operation = operation;
    }
    public void doOperation() {
        Method m = operation.getClass().getMethod("execute");
        m.invoke(operation);
    }
}
like image 79
Appu Mistri Avatar answered Oct 02 '22 03:10

Appu Mistri