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 {

// ...

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值