description:
- I need declear a list maybe bound mutiple types.One type in each run.
pseudo-code:
// first run
String Type = "Foo";
List<Type> results = new ArrayList<Type>();// want to declear a `List<Foo>` variable here
// second run
String Type = "Bar";
List<Type> results = new ArrayList<Type>();// want to declear a `List<Bar>` variable here
what I have tried:
- use switch
Foo.java
public class Foo {
}
Bar.java
public class Bar {
}
test.java
public class test{
public static void main(String[] args) {
String type = "Bar";
switch (type){
case "Bar":
List<Bar> barResults = new ArrayList<>();
Bar tempBar = new Bar();
barResults.add(tempBar);
System.out.println(barResults);
break;
case "Foo":
List<Foo> fooResults = new ArrayList<>();
Foo tempFoo = new Foo();
fooResults.add(tempFoo);
System.out.println(fooResults);
break;
}
}
- I think it works (not 100% comfirmed), but it will cause a lot of duplicated code.
- Use reflection and extract a function
public class test{
public static void main(String[] args) {
try {
Class<?> type = Class.forName("Bar");
List<?> result = new test().mytry(type);
System.out.println(result);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
public List<?> mytry(Class<?> classname) {
List<Object> results = new ArrayList<>();
try {
Object obj = classname.getDeclaredConstructor().newInstance();
results.add(obj);
return results;
} catch ( NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
- I can't comfirm whether it works or not.
- Use map
question:
- How to declear a list of specific class base on classname?
Aucun commentaire:
Enregistrer un commentaire