Generate getter / setter in Java (again)

I'm thinking about writing

class MyClass {
  @Get
  @Set
  protected int aValue;
}

Then, get is automatically generated for the class_ Avalue() and set_ Avalue() method

I found these possibilities:

1A) at compile time Use the annotation processor to process MyClass Java, and then write a new MyClass Java, finally use the latter (replace with the original text) and The rest of Java

1b) at compile time Use the annotation processor to generate a myclassgenerated Java file, which contains a new class (using the get / set method), which is a subclass of the original MyClass

2) At run time Using Java Lang. instrument and external tools (such as BCEL) are in MyClass Class

Well, the problem is: considering that I don't want to use third-party libraries (such as Lombok project or BCEL) as much as possible

a) Did I miss the other way?

b) Which method would you use?

I think I'll use 1a) because

1b) unclean (the rest of the program should use myclassgenerated instead of the original MyClass, although it may be just a matter of name)

2) It's really hard (for me, at least)

Solution

You missed something. If you want to go down this road, I will say this is the best way:

1c) at compile time Compile the class normally, and then modify it using apt annotation processor Class file instead of the source file to add the appropriate get and set methods to the bytecode

In this way, your source code remains in its original state, you don't have to use temporary files, and the actual compiled classes are as you want

However, this is to open the nut with a sledgehammer It is feasible, but now your code is not strictly Java. If someone accepts and runs javac, they will get a class without getter and setter This will make debugging difficult because all line numbers will screw up. Unless you are very sure that you have done the right operation with the annotation processor, you can't even see the source code of getters and setters Correct the error The static analysis tool will tell you that the property has never been used, and so on

I'm a general consensus - just use the methods provided by each ide to generate them in the source file This is less time than writing comments, and every developer and tool can understand this Java has no properties - overcome it

The above is all the contents of generating getter / setter (again) in Java collected and sorted by programming house for you. I hope this article can help you solve the program development problems encountered in generating getter / setter (again) in Java.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>