Eug*_*e S 5 java lambda design-patterns java-8
我有一个依赖于某个库的大型项目.其中一个库类暴露了以下方法:
public void until(final Predicate<T> isTrue)
public <V> V until(Function<? super T, V> isTrue) {
Run Code Online (Sandbox Code Playgroud)
在哪里Predicate和Function是:
com.google.common.base.Predicate<T>
com.google.common.base.Function<? super T, V>
Run Code Online (Sandbox Code Playgroud)
在该库的最后一个版本中,上述内容已经更改,并通过弃用(删除)public void until(final Predicate<T> isTrue)方法和修改第二个方法进行了重构,如下所示:
public <V> V until(Function<? super T, V> isTrue)
Run Code Online (Sandbox Code Playgroud)
功能现在在哪里java.util.function.Function<? super T, V>.
据我所知,上述更改已完成,以完全支持Java 8功能,特别是lambda表达式.
现在问我的问题.虽然我可以将所有until使用此方法的已弃用版本的调用转换为新结构,但我担心调用此方法的位置太多.有没有办法可以继续使用旧的(已弃用的)方法,也许可以在其他地方重新声明它或某种类型的东西?任何可以解决这个问题的方法都很乐意接受.
如果您不想更改源代码,一种可能的解决方案是从until(Function)源代码中具有方法的类库中复制源代码。然后until(Predicate)在源代码中添加删除的方法。最终代码如下:
package ???;//the package of the library which class have `until` method
class ??? {//the class copied from the library which have `until` method
<T> boolean until(Predicate<T> predicate){
return until(new Function<T,Boolean>(){
public Boolean apply(T value){
return predicate.apply(value);
}
});
}
<T,R> R until(Function<T,R> function){
// the source code from the library
}
//... other source code from the library
}
Run Code Online (Sandbox Code Playgroud)
将ClassLoader仅加载从库复制的类,而不是从库复制。因为ClassLoader使用委托模型来搜索类/资源,并且AppClassLoader总是会在类路径中找到一个类,然后依次找到外部 jar:
该类
ClassLoader使用委托模型来搜索类和资源。的每个实例ClassLoader都有一个关联的父类加载器。当请求查找类或资源时,实例会将类或资源ClassLoader的搜索委托给其父类加载器,然后再尝试查找类或资源本身。虚拟机的内置类加载器称为“引导类加载器”,它本身没有父类加载器,但可以充当实例的父类加载器。ClassLoader
另一种选择是编写您自己的ClassLoader,然后编写一个代理来访问您的库类。当您无法复制外部库类时,这很有用,因为它依赖于许多内部类。例如,假设您有一个库类,如下所示:
public class Library<T> {
private final List<T> items;
public Library(T... items) {
this.items = Arrays.asList(items);
}
public boolean exists(Function<? super T, Boolean> condition) {
return items.stream().anyMatch(condition::apply);
}
}
Run Code Online (Sandbox Code Playgroud)
然后声明一个接口来匹配库类,如下所示:
public interface LibraryAccess<T> {
boolean exists(Function<? super T, Boolean> condition);
}
Run Code Online (Sandbox Code Playgroud)
最后编写自己的类覆盖库类,如下所示:
public class Library<T> {
private final LibraryAccess<T> library;
public Library(T... items) {
// create library from external jars by your own ClassLoader & reflect api
library = LibraryAccess.newInstance(items);
}
public boolean exists(Predicate<? super T> condition) {
return library.exists(condition::test);
}
public boolean exists(Function<? super T, Boolean> condition) {
return library.exists(condition);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |