参数化的泛型类实例可以根据类型参数使用不同的方法? [英] Can parameterized generic class instance have different methods depending on type argument?
问题描述
在回答以下问题时:
我如何创建一个可以构建多种Java对象的构建器?我认为在Java中实现以下功能是不可能的:
$ b
public class Builder< T> {
// ...
}
Builder<用户> userBuilder = new Builder< User>();
//这里userBuilder只有方法'name'
userBuilder.name(John);
Builder< Country> countryBuilder = new Builder< Country>();
//这里countryBuilder只有方法'code'
countryBuilder.code(UA);
但是,在评论中,用户 John Feminella 说过,它实际上可以使用自定义类加载器。
现在,我了解Java中类加载器的基础知识,但真的不知道他们如何改变Java语法。有人可以给出如何实现这个基本想法吗?
预先致谢!
不需要长的代码片段 - 使用标准术语做简短的解释就可以了。
原因很难,因为Java的内置一旦添加了类,类加载器就不会重新加载类,并且需要重新加载类(在Java中)才能动态添加方法。此外, ClassLoader.resolve()
方法是 final
,这意味着自定义类加载器无法覆盖它。这有很多效果,但最重要的是,如果你想重新加载一个类,你必须每次 实例化一个新的 ClassLoader
你想加载它。
这非常昂贵,所以没有实际的理由尝试以这种方式解决Java的局限性。 (你应该使用更适合于这种工作的另一种语言,比如JRuby。)动态加载东西是可能的,但它不值得。
但是,假设你愿意忍受一些痛苦,你能做到吗?绝对。请参阅此文章。使用的策略是:
- 在运行时编译Java代码
- 加载/重载Java类在运行时通过代理类
- 将最新的类链接到其调用者
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.
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
这篇关于参数化的泛型类实例可以根据类型参数使用不同的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!