Java如何使用字符串值作为类名与变量名生成目标代码
解决方案:动态替换代码中的类名与变量名
根据你给出的字符串变量和目标代码,我们可以通过精准文本替换或者代码层面的字符串拼接来实现需求,下面分两种场景说明:
1. 直接替换后的最终代码
按照你指定的映射关系逐一替换:
CustomTextInputLayout→android1的值:TextInputLayoutTextInputEditText→android2的值:TextInputEditText(和原变量值一致,替换后无变化)textInputEditTextemail→android1var的值:customTextInputLayoutemailcustomTextInputLayoutemail→android2var的值:textInputEditTextemail
替换完成的代码如下:
TextInputLayout textInputEditTextemail = null; TextInputEditText customTextInputLayoutemail = null; textInputEditTextemail = new TextInputLayout(this); textInputEditTextemail.setLayoutParams(new TextInputLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)); customTextInputLayoutemail = new TextInputEditText(this); customTextInputLayoutemail.setHint(""); textInputEditTextemail.addView(customTextInputLayoutemail); textInputEditTextemail.setHelperText("min "+MIN_PASSWORD_LENGTH+" characters");
2. 代码层面动态生成(字符串拼接方式)
如果是想在Java代码里通过变量动态生成这段代码,可以用字符串拼接的方式实现,示例代码如下:
String android1="TextInputLayout"; String android1var = "customTextInputLayoutemail"; String android2="TextInputEditText"; String android2var = "textInputEditTextemail"; // 拼接生成目标代码字符串 String generatedCode = android1 + " " + android2var + " = null; " + android2 + " " + android1var + " = null; " + android2var + " = new " + android1 + "(this); " + android2var + ".setLayoutParams(new " + android1 + ".LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT)); " + android1var + " = new " + android2 + "(this); " + android1var + ".setHint(\"\"); " + android2var + ".addView(" + android1var + "); " + android2var + ".setHelperText(\"min \"+MIN_PASSWORD_LENGTH+\" characters\");"; // 可输出或直接使用生成的代码字符串 System.out.println(generatedCode);
这样就能完全按照你的要求完成类名和变量名的替换啦。
内容的提问来源于stack exchange,提问作者Santhosh
相关产品推荐
相关产品推荐

