简体   繁体   中英

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?

I mean, if they're a POJO one class setters should take the other class getters as arguments.

Is there a Pattern for this situation?

The Apache Bean Utilities package has a tool for this.

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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