代码之家  ›  专栏  ›  技术社区  ›  Santhosh

Java:如何使用字符串值作为类名和变量名

  •  -3
  • Santhosh  · 技术社区  · 6 年前

    我有字符串变量

    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 回复  |  直到 6 年前
        1
  •  0
  •   Abu Yousuf    6 年前

    使用 Reflection 动态创建视图。得到 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();
        }
    
        2
  •  0
  •   Chris Gomez    6 年前

    可以使用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 });