Can parameterized generic class instance have different methods depending on type argument?

廉价感情. 提交于 2019-12-12 02:57:19

问题


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<T> {
     // ...
}

Builder<User> userBuilder = new Builder<User>();
// here userBuilder only has method 'name'
userBuilder.name("John");

Builder<Country> countryBuilder = new Builder<Country>();
// 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.


回答1:


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


来源:https://stackoverflow.com/questions/25920002/can-parameterized-generic-class-instance-have-different-methods-depending-on-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!