Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It doesn't work because T could be any type, and Java is statically typed. The compiler has no idea whether you'll try to create a SceneNode<String> - then what would execute do?

One option is to create an appropriate interface, e.g.

public interface Executable {
    void execute();
}

and then to constrain T in SceneNode to implement Executable:

public class SceneNode<T extends Executable> {
    ...
}

(I find it a little bit odd that T has to extend Executable rather than implement it in the source code, but then T could end up being an interface itself, so I guess it makes sense.)

Then it should work fine. Of course you could make Executable an abstract superclass instead - or even a (non-final) concrete class - if you wanted, but I would generally prefer to use an interface unless I had some reason not to.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...