【问题标题】:JavaPoet : How to add a field of type class , but I have only the class name, not the class?JavaPoet:如何添加类类型的字段,但我只有类名,没有类?
【发布时间】:2018-10-12 19:49:37
【问题描述】:
String fieldName = (fieldchild.getAttribute("Name")); //gives field name : opcode

String fieldCustomID = (fieldchild.getAttribute("ID")); //gives id: 2022

String classTypeofField = IdNameMappingList.get(fieldCustomID).toString(); //give class name OpCodeClass

FieldSpec fieldSpec = FieldSpec.builder(**some code**, fieldName)
                                                        .build();

应该给出类似

OpCodeClass opcode;

也欢迎任何其他解决方法。

【问题讨论】:

  • 您不需要实际的类,但您确实需要它的完全限定名称(例如“org.package.OpCodeClass”),因为 JavaPoet 还必须生成导入语句为班级。使用包名和类名,您可以创建一个ClassName 对象以传递给FieldSpec 构建器。如果您确定不需要导入(例如,您生成的类与所有操作码类在同一个包中),您可以在不使用 FieldSpec 的情况下将该字段编写为文字。另一种可能性是 search the class via reflection 根据其名称。

标签: java javapoet


【解决方案1】:

尝试ClassName.get("com.company.app", classTypeofField),将包名替换为类名。

【讨论】:

  • 谢谢。这有帮助。
猜你喜欢
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 2015-05-20
  • 2019-11-19
  • 1970-01-01
  • 2015-09-11
相关资源
最近更新 更多