Frithjof
Frithjof

Reputation: 2264

Creating a function with Object<?> parameter

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

Answers (2)

James Dunn
James Dunn

Reputation: 8294

Your code has multiple mistakes:

  1. You have parenthesis () after you class declarations.
  2. You're trying to give generic parameters to Object, which doesn't have generic parameters.

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

user2768995
user2768995

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

Related Questions