简体   繁体   中英

Create dynamic Type Java

explain my problem:

I have a super abstract class called First and then I have a lot of class that inherit from it. I want to build a method that I "say" to it "create a ArrayList of one of the types that inherit from First class", but I'm not to able to find solution. For example:

public abstract class First{

   public First(){
   }
}

public class FirstOne extends First{

   ...........
}

//It's a pseudo-code
public class MyProgramClass{

   public creatingMethod(TypeThatInheritFromFirstClass x ){
      return ArrayList<TypeThatInheritFromFirstClass>;
   }
}

I insert creatingMethod in program class,but it can be anywhere(I prefer in First class like static method, but it's an example)

Thank for your time

You could use a type token :

public class SomeGenerics {
    public static void main(String[] args) {
        List<SubFirst1> list1 = creatingMethod(SubFirst1.class);
        List<SubFirst2> list2 = creatingMethod(SubFirst2.class);
    }
    public static <T extends First> List<T> creatingMethod(Class<T> type) {
        return new ArrayList<>();
    }
}

class First {}
class SubFirst1 extends First {}
class SubFirst2 extends First {}

EDIT as per the comment:

As you already have the type token , you can use it for creating instances of that type. A little restriction is, that you must know what constructor to use. If they - for example - all have a parameterless constructor, you can create instances like that:

public static <T extends First> List<T> creatingMethod(Class<T> type) throws ReflectiveOperationException {
    List<T> result = new ArrayList<>();
    result.add(type.newInstance());
    return result;
}

If you have a constructor with parameters (again: all sub classes must have the same parameterized constructor), you must go a more difficult way. Example with a string parameter:

public static <T extends First> List<T> creatingMethod(Class<T> type, String param) throws ReflectiveOperationException {
    List<T> result = new ArrayList<>();
    Constructor<T> constructor = type.getDeclaredConstructor(String.class);
    result.add(constructor.newInstance(param));
    return result;
}

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