I often find myself wanting to copy a living java object into my tests (in the source code). I doubt this is generally doable, but perhaps a asJavaSourceCode()
method could be generated for all @AutoValue
objects?
Here is some code to demonstrate what I want.
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Person {
public abstract String name();
public abstract Integer age();
public static Person create(String name, Integer age) {
return new AutoValue_Person(name, age);
}
public String asJavaSourceCode() {
// Can this code be automatically generated?
return "Person.create(\"" + name() + "\"," + age() + ")";
}
public static void main(String[] args) {
System.out.println(Person.create("Jordan", 29));
System.out.println(Person.create("Jordan", 29).asJavaSourceCode());
}
}
When running this I get.
Person{name=Jordan, age=29}
Person.create("Jordan",29)
I would consider any of these a valid answer to this question:
- "Yes, here's a library link"
- "No, it doesn't exist yet"
- "Somebody else did something similar."
- "That is bad practice, don't do it, see Effective Java Book Item XYZ"