Reputation: 2264
I have a main class like this:
public class MainClass() {
public Class<? extends Object> myType;
// This does not work, but thats what I want:
public MainClass(Class<? extends Object> type) {
myType = type;
}
public void myMethod(Object<myType> myParameter) {
// Do stuff
}
}
And some classes extending this class, for example:
public class ChildClass() extends MainClass {
public ChildClass() {
super((Class<? extends Object>) String.class);
// this should be changeable to what ever class then String.class
}
}
How do you create a parent method with a variable class type?
The code myMethod(Object<myType> obj);
does not work.
Upvotes: 0
Views: 92
Reputation: 8294
Your code has multiple mistakes:
()
after you class declarations.Additionally, you should try declaring a generic type (like `T`) instead of using `?`. Try this:
public class MainClass<T extends Object> {
public Class<T> myType;
public MainClass(Class<T> type) {
myType = type;
}
public void myMethod(T myParameter) {
// Do stuff
}
}
class ChildClass extends MainClass<String> {
public ChildClass() {
super(String.class);
// this should be changeable to what ever class then String.class
}
}
Also, please note, `T extends Object` is totally redundant, but I left it in since you want it.
Upvotes: 3
Reputation:
you should do it like this :
public class MainClass<T> {
public void myMethod(T myParameter) {
// Do stuff
}
}
public class ChildClass extends MainClass<String> {
}
Upvotes: 2