你不必使用任何第三方库,因为Java
拥有反射(reflections)。此方法将为您完成所有操作,并轻松创建UI
:
for(String s : arrayWithNames){
View view = createViewInstance(0, s);
if(view instance of View){
}else{
}
}
关于 createViewInstance()
:
private View createViewInstance(String name){
View view = null;
try{
if(name.equalsIgnoreCase("View"){
Class viewClass = Class.forName("android.view." + name);
view = (View) viewClass.getConstructor(Context.class).newInstance(new Object[]{ctx});
}else{
Class viewClass = Class.forName("android.widget." + name);
view = (View) viewClass.getConstructor(Context.class).newInstance(new Object[]{ctx});
}
} catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException
| InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return view;
}
就是这样。您已经拥有了处理任何类型的 View
的所有内容。
我已经测试过上面的代码并在项目中使用过。它完美运行。
与其他 Object
相同的情况。您无法使用反射创建 int
,但可以创建 Integer
,因此基本上是相同的。
其中一个问题是除了 View
和 ViewGroup
之外,还有更多类型。但这也取决于您要创建多少种类型的 Object
... 在给定的示例中,假设我将执行 char
、String
、int
、Object
,然后您可以轻松扩展它。
for(String s : arrayWithNames){
if(s.equalsIgnoreCase("int")){
Integer integer = (Integer)createVarInstance(s);
}else if(s.equalsIgnoreCase("String"){
String string = (String)createVarInstance(s);
}else if(s.equalsIgnoreCase("char"){
Character character = (Character)createVarInstance(s);
}else if(s.equalsIgnoreCase("Object"){
Object object = (Object)createVarInstance(s);
}
}
由于所有这些数据类型都在同一个包中,这使得我们的工作更加容易。方法 createVarInstance()
:
private Object createVarInstance(String name){
Object obj = null;
try{
Class varClass = Class.forName("java.lang." + name);
object = (Object) varClass.newInstance();
} catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException
| InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return object;
}
如果需要的话,可以为不同的包制作一个通用的方法。
如果将来您想创建更多不同类型的变量,这些变量位于不同的包中,那么您将不得不检查名称或执行与
View
类似的操作。