The short answer is no . What you ask for is impossible. Reflection considers the code at runtime and dynamically calls methods; it cannot generate actual methods.
What could you do:
Foo foo = ReflectiveBuilder.from(Foo.class). set("id", 1). set("title", "title"). build();
This has three massive problems:
String fields - a typo causes a runtime error, not a compilation time,Object values - the wrong type causes a runtime error, not a compilation time, and- it will be much slower than the alternative, since the reflection is very slow.
Thus, a reflection-based solution, although possible (see Apache Commons BeanUtils BeanMap ), is not at all practical.
Long answer, if you are willing to allow some compile-time magic, you can use Project Lombok . Lombok's idea is to create template code from annotations using the Java annotation preprocessor.
It is truly magical that all IDEs, and at least the big 3, understand that annotation preprocessing and code completion will function correctly even if the code really does not exist.
In the case of POJO with Builder you can use @Data and @Builder
@Data @Builder public class Foo { public int id; public String title; public boolean change; ... }
The @Data will generate:
- necessary argument constructor (which accepts all
final fields) equals and hashCode that use all fields (can be customized using the @EqualsAndHashCode annotation)- a
toString for all fields (can be configured using @ToString annotations and public getters and seters for all fields (can be configured using the @Getter / @Setter in the fields).
The @Builder will generate an inner class called Builder , which can be created using Foo.builder() .
Make sure you configure the equals , hashCode and toString methods as if you had two classes with Lombok that have references to each other, then you end the endless loop in the default case, since both classes include other methods .
There is also a new configuration system that allows you to use, for example, fusible setters, so that you can no longer use if your POJO is changed:
new Foo().setId(3).setTitle("title)...
For another approach, you can look at Aspect Oriented Programming (AOP) and AspectJ . AOP allows you to chop your classes into “aspects,” and then stick to them together using specific rules using a pre-compiler. For example, you can accurately implement what Lombok does using custom annotations and aspect. However, this is a rather complicated topic, and it is quite possible to overdo it.