简体   繁体   中英

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.

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.

you should do it like this :

public class MainClass<T> {
  public void myMethod(T myParameter) {
    // Do stuff
  }
}

public class ChildClass extends MainClass<String> {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM