1

The class TrainingData has an attribute intent which can be of any of the subtypes of class Intent. I am trying to use Java Generics to enforce that the generic type T can only be a sub-class of Intent. How can I do that?

public class TrainingData<T> extends Data { private T intent; private String id; public TrainingData (UserCommand userCommand, T intent) { super(userCommand); this.intent = intent; } public Klass getKlass() { return intent.getKlass(); // <-- THIS WORKS ONLY IF T extends from Intent } public Intent getIntent() { return intent; } public void setIntent(Intent intent) { this.intent = intent; } @Override public String toString() { return "TrainingData [intent=" + intent + ", id: " + id + "]"; } } 
1

2 Answers 2

6

The class TrainingData has an attribute intent which can be of any of the subtypes of class Intent.

Try with T extends Intent that means any class that extends Intent are accepted.

public class TrainingData<T extends Intent> extends Data {...} 

Read more Java Tutorial Bounded Type Parameters


Change it for getter & setter methods as well.

class TrainingData<T extends Intent> extends Data { private T intent; public T getIntent() { return intent; } public void setIntent(T intent) { this.intent = intent; } ... } 
Sign up to request clarification or add additional context in comments.

Comments

1

I think it's like this:

public class TrainingData<T extends Intent> 

See http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html for more info.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.