简体   繁体   English

转换实现相同接口的类的快速方法

[英]Quick method to convert classes implementing same interface

How, in Java, to quickly (or generically) convert one class that implements an interface into another class that implements the same interface? 在Java中,如何快速(或通用地)将实现接口的一个类转换为实现相同接口的另一个类?

I mean, if they're a POJO one class setters should take the other class getters as arguments. 我的意思是,如果它们是POJO,则一个类的设置者应将另一个类的获取器作为参数。

Is there a Pattern for this situation? 有这种情况的模式吗?

The Apache Bean Utilities package has a tool for this. Apache Bean Utilities软件包为此提供了一个工具。

org.apache.commons.beanutils.BeanUtils
    .BeanUtils.copyProperties

public static void copyProperties(Object dest, Object orig)
                       throws IllegalAccessException,
                              InvocationTargetException

Copy property values from the origin bean to the destination bean for all cases where the property names are the same.

For more details see BeanUtilsBean.

Parameters:
    dest - Destination bean whose properties are modified
    orig - Origin bean whose properties are retrieved 

I believe that the pattern for this situation is called a Proxy : 我相信这种情况的模式称为Proxy

A proxy, in its most general form, is a class functioning as an interface to another thing. 在最一般的形式上,代理是一个类,它充当另一件事的接口。 The other thing could be anything: a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate. 另一件事可能是任何东西:网络连接,内存中的大对象,文件或其他昂贵或无法复制的其他资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM