Recently developed a demand to obtain the name of the class attribute, but just wants to call it simply and conveniently.
For example, a physical category user contains two properties: ID and username. Now you want to obtain a string of the two attribute names of “ID” and “username”.
Thinking of LOMBOK’s good effect in simplifying the physical class through annotations, so I want to find whether LOMBOK has any annotations to achieve this needs.
After the retrieval of Baidu+Google@FieldNameConstants
Meet demand.
@fieldnameconstants official website introduction
LOMBOK different versions for annotations@FieldNameConstants
The effect will be different.
The chapterSmall print
chapter gives the iteration of the historical version. The LOMBOK version used in this article is 1.18.16
Plagiarism official code DEMO1
import lombok.experimental.FieldNameConstants;
import lombok.AccessLevel;
@FieldNameConstants
public class FieldNameConstantsExample {
private final String iAmAField;
private final int andSoAmI;
// Add @FieldnameConstants.exClude This comment indicates that the attribute name does not need to provide attribute name
@FieldNameConstants.Exclude
private final int asAmI;
}
Plagiarism of the official DEMO2, the following code is the final Java code effect after LOMBOK uses the annotation. In essence, a internal class is generatedFields
。
public class FieldNameConstantsExample {
private final String iAmAField;
private final int andSoAmI;
private final int asAmI;
public static final class Fields {
public static final String iAmAField = "iAmAField";
public static final String andSoAmI = "andSoAmI";
}
}
Call with junit
package lombok.fieldNameConstatns;
import org.junit.Test;
public class LombokConstantsTest {
@Test
public void constatnsTest(){
System.out.println(FieldNameConstantsExample.Fields.iAmAField);
// Output content: IAMAFIELD
// Since the previous code clip AsaMi field was modified by @fieldnameconstants.exclude, it cannot be called
// system.out.println (FieldnameConstantSexample.fields.asami); // Can't get the asami attribute! Intersection
}
}
can see the output stringiAmAField
is completely consistent with the case of the statement.
- If you want to use enumeration type: @Fieldnameconstants (asnum = true)
- If you want to use the output result of the full -write, modify the LOMBOK configuration, the annotation method cannot be configured!
lombok.fieldNameConstants.uppercase = true
- The default internal class name is
Fields
, and it istwenty four# . If you want to modify temporarily, you can use the annotation configuration:
public
@FieldNameConstants(innerTypeName = "FieldNames", access = AccessLevel.PACKAGE)
; If you want to modify the internal class name uniformly, you can modify the LOMBOK configuration file
lombok.fieldNameConstants.innerTypeName