While answering following question:
How do I create a Builder that can build more than one kind of Java object? I thought that it's impossible to achieve the following in Java:
public class Builder {
// ...
}
Builder userBuilder = new Builder();
// here userBuilder only has method 'name'
userBuilder.name("John");
Builder countryBuilder = new Builder();
// here countryBuilder only has method 'code'
countryBuilder.code("UA");
But, in the comments, user John Feminella told that it is actually possible using custom class loaders.
Now, I know basics of class loaders in Java, but really have no idea how they can alter Java syntax. Could someone give basic idea on how this can be achieved?
Thanks in advance!
P.S. No need for long code snippets - short explanation using standard terms would do.
解决方案
The reason it's hard is because Java's built-in classloader will not reload a class once it's been added, and reloading a class is required (in Java) to add methods dynamically. Furthermore, the ClassLoader.resolve() method is final, meaning a custom class loader can't override it. This has a number of effects, but the most important one is that if you want to reload a class, you must instantiate a new ClassLoader every time you want to load it.
That's enormously expensive, so there's really no practical reason to try and work around the limitations of Java this way. (You should be using another language more suited to this sort of work, like JRuby.) Dynamically loading things is possible, but it's just not worth it.
But, assuming you're willing to suffer some pain, can you do it? Absolutely. See, e.g., this article. The strategy used there is to:
compile Java code at runtime
load/reload Java class at runtime via a proxy class
link the up-to-date class to its caller