如何在多个Java类中自动修改代码?

huangapple go评论79阅读模式
英文:

How to modify code automatically in multiple java classes?

问题

我有一个对象层次结构,或者树形结构,我想做两件事:

  1. 对于每个节点,将每个公共字段变为私有,并生成getter和setter。
  2. 将树的所有状态保存在一个<String,Object>映射中,以便每次对节点之一的setter或getter进行调用时都会访问映射,并且不会从节点本身保存或检索状态。我会这样做是将对映射的引用注入到树中的每一个节点中,并让setter和getter操作映射。

我想知道是否有一种方法可以自动修改我的代码来实现这些。我知道IntelliJ可以将类中的所有公共字段变为私有,并为一个文件生成getter和setter,但是否可能对多个文件进行这样的操作?是否可能自动进行我所概述的第二次修改?

英文:

I have an object hierarchy, or tree, for which I'd like to do two things:

  1. For every node make every public field private and generate getters and setters.
  2. Save all state of the tree in a <String, Object> map so every time a setter or getter is invoked on one of the nodes it goes to the map and doesn't save or retrieve the state from the node itself. The way I would do this is to inject a reference to the map into every one of the nodes in the tree and have the setters and getters operate on the map.

I'm wondering if there's a way to modify my code automatically to do this. I know IntelliJ can make all public fields in a class private and generate getters and setters for one file, but is it possible to do this for many? Is it possible to do the second modification I outlined automatically?

答案1

得分: 2

你可以使用IntelliJ的getter/setter模板来实现这一点。
这是一个相当清晰的伪代码工具,用于创建自定义代码生成机制。
参考这个问题以更清楚地了解。

英文:

You could do this using IntelliJ-template for getter/setter.
It's a pretty clear pseudo-code tool to create a custom code-generation mechanic.
See this question to understand more clear

答案2

得分: 0

你可以使用ByteBuddy来完成这个任务。

英文:

You could use ByteBuddy to accomplish this.

huangapple
  • 本文由 发表于 2020年4月7日 19:36:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/61079176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定