java:如何使用String值作为类Name和变量名

时间:2018-05-23 14:02:50

标签: java android

我有像

这样的String变量
String android1="TextInputLayout";
String android1var = "customTextInputLayoutemail"
String android2="TextInputEditText";
String android2var = "textInputEditTextemail"

我想创建以下代码:

CustomTextInputLayout customTextInputLayoutemail = null;
TextInputEditText textInputEditTextemail = null;

customTextInputLayoutemail = new CustomTextInputLayout(this);
customTextInputLayoutemail.setLayoutParams(new CustomTextInputLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));

textInputEditTextemail = new TextInputEditText(this);
textInputEditTextemail.setHint("");
customTextInputLayoutemail.addView(textInputEditTextemail);
customTextInputLayoutemail.setHelperText("min "+MIN_PASSWORD_LENGTH+" characters");

我如何替换

class Name CustomTextInputLayout with android1
class Name TextInputEditText with android2

variable Name textInputEditTextemail with android1var
variable Name customTextInputLayoutemail with android2var

2 个答案:

答案 0 :(得分:0)

您可以使用Class.forname()来使用字符串名https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)来获取类。 像这样:

Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });

答案 1 :(得分:0)

使用Reflection动态创建View。要constructor使用getConstructor并使用newInstance方法创建实例。

示例代码:

    String android1="TextInputLayout";
    try {
        Class<?> clazz = Class.forName("android.support.design.widget." + android1);
        Constructor<?> constructor = clazz.getConstructor(Context.class);
        Object object = constructor.newInstance(getContext());

        if (object instanceof TextInputLayout) {
            TextInputLayout textInputLayout = (TextInputLayout) object;
        }else {   
        }

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (java.lang.InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }