You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何使用字符串值作为类名与变量名生成目标代码

解决方案:动态替换代码中的类名与变量名

根据你给出的字符串变量和目标代码,我们可以通过精准文本替换或者代码层面的字符串拼接来实现需求,下面分两种场景说明:

1. 直接替换后的最终代码

按照你指定的映射关系逐一替换:

  • CustomTextInputLayout → android1的值:TextInputLayout
  • TextInputEditText → android2的值:TextInputEditText(和原变量值一致,替换后无变化)
  • textInputEditTextemail → android1var的值:customTextInputLayoutemail
  • customTextInputLayoutemail → 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:47:20