I have a number of methods, each of which checks the same set of conditions and returns a null value if none of the conditions are met, otherwise returns an object of different classes.
Is there a way to not have to write all of these terms for each function and use less code?
public A methode1()
{
if ///something
return A("xxx")
else if ///something
return A("yyy")
else if ///something
return A("zzzz")
else
return Error() // or return null
}
public B methode2()
{
if ///something
return B("mmmm")
else if ///something
return B("nnn")
else if ///something
return B("bbbb")
else
return Error() // or return null
}
public C methode3()
{
if ///something
return C("oooo")
else if ///something
return C("ggg")
else if ///something
return C("llll")
else
return Error() // or return null
}
You can combine template method pattern with generics:
public abstract class AbstractTemplate<T>
{
public T methode()
{
if ///something
return Do1();
else if ///something
return Do2();
else if ///something
return Do3();
else
return Error() // or return null
}
protected abstract T Do1();
protected abstract T Do2();
protected abstract T Do3();
}
public class ConcreteATemplate : AbstractTemplate<A>
{
protected override T Do1() => A("xxx");
protected override T Do2() => A("yyy");
protected override T Do3() => A("zzzz");
}
And use it inside your methods:
public A methode1() => new ConcreteATemplate().methode(); // also can "cache" instance in your case in static readonly field.
Standard approch is , you can use a factory class with interface/abstract class
public interface IOutput {
}
public class Output1 : IOutput{
}
public class Output2 : IOutput{
}
public class MyFactory
{
public IOutput Get()// add args list of any
{
if(condition) // you can use args in condition if necessary
return new Output1();
else
return new Output2();
}
}
You can use generic method and repository pattern. Here is a generic method example with C#. I think it may give you some idea..
public static async Task<List<ObjectType>> GetDataList<ObjectType>(UserAuthorization token) where ObjectType : BaseModel
{
List<ObjectType> data = new List<ObjectType>();
try
{
if(token.UserTypes.Count > 0)
{
Type genericClass = typeof(Repository<>);
Type constructedClass = genericClass.MakeGenericType(typeof(ObjectType));
MERPDbContext mERPContext = new MERPDbContext();
var created = (Repository<ObjectType>)Activator.CreateInstance(constructedClass, mERPContext);
if (token.UserTypes[0].Id == (byte)UserTypes.SuperAdmin)
{
var sub = await created.GetAsync();
data = sub.ToList();
}
else if (token.UserTypes[0].Id == (byte)UserTypes.InstituteAdmin)
{
data = await created.FilterListAsync
(x => x.InstituteId == token.InstituteID);
}
else
{
data = await created.FilterListAsync(x =>
x.InstituteId == token.InstituteID && x.CampusId == token.CampusID);
}
}
}
catch (Exception e)
{
}
return data;
}
You could use a method with a generic type parameter and a set of initial values.
private T GetIfOkay<T>(string a, string b, string c)
where T : new()
{
if (something)
return new T(a);
else if (something else)
return new T(b);
else if (yet something else)
return new T(c);
else
return null;
}
public A methode1()
{
return GetIfOkay<A>("xxx", "yyy", "zzzz");
}
public B methode2()
{
return GetIfOkay<B>("mmmm", "nnn", "bbbb");
}
// etc.
If you need a more dynamic behaviour, #donggas90's solution.
See:
Generic Methods (C# Programming Guide)
C# Generics (TutorialsTeacher)
According to your comment, I tried to rewrite your sample, hope this will help you. ask freely if you need more clarity.
class Program
{
static void Main(string[] args)
{
var objFactory = new MyFactory();
// Get and cast return object
A a1= (A) objFactory.ConsolidatedMethod("Condition 1 for Objct A", "xxx");
// Or Directly assian to base object
IOutput a2 = objFactory.ConsolidatedMethod("Condition 2 for Objct A", "yyyy");
// use anonymous object
var b1= objFactory.ConsolidatedMethod("Condition 1 for Objct B", "mmmm");
var nullcheck1 = objFactory.ConsolidatedMethod("null conditionj", "i'm null");
}
}
interface IOutput
{
}
class A : IOutput
{
public A(string objParam)
{
}
}
class B : IOutput
{
public B(string objParam)
{
}
}
class NullOutput : IOutput
{
public NullOutput(string objParam)
{
}
}
class MyFactory
{
/// <summary>
/// Demo
/// </summary>
/// <param name="arg">you can use this based on your requirement </param>
/// <param name="objparam">you can use this based on your requirement </param>
/// <returns>IOutput</returns>
public IOutput ConsolidatedMethod(string arg, string objparam)
{
IOutput _output=default;
if (arg == "Condition 1 for Objct A")
_output = new A(objparam);
else if (arg == "Condition 2 for Objct A")
_output = new A(objparam);
else if (arg == "Condition 1 for Objct b")
_output = new B(objparam);
else if (arg == "Condition 2 for Objct B")
_output = new B(objparam);
else
_output = new NullOutput(objparam);
return _output;
}
}
Related
I have these 3 methods which all have the same logic. The only difference is that a different parameter type is passed in:
public static String calculateAmount(QRequest qRequest) {
if (qRequest.getValue() == null) {
return 300_VALUE;
}
if (qRequest.getValue().getOptionalCodes().contains(125_CODE)
&& qRequest.getValue().getOptionalCodes().contains(600_CODE)) {
throw new ServiceException("Multiple options received");
}
if (qRequest.getValue().getOptionalCodes().contains(125_CODE)) {
return 125_VALUE;
} else if (qRequest.getValue().getOptionalCodes().contains(600_CODE)) {
return 600_VALUE;
} else {
return 300_VALUE;
}
}
public static String calculateAmount(CState cState) {
if (cState.getValue() == null) {
return 300_VALUE;
}
if (cState.getValue().getOptionalCodes().contains(125_CODE)
&& cState
.getValue()
.getOptionalCodes()
.contains(600_CODE)) {
throw new ServiceException("Multiple options received");
}
if (cState.getValue().getOptionalCodes().contains(125_CODE)) {
return 125_VALUE;
} else if (cState
.getValue()
.getOptionalCodes()
.contains(600_CODE)) {
return 600_VALUE;
} else {
return 300_VALUE;
}
}
public static String calculateAmount(RState rState) {
if (rState.getValue() == null) {
return EXCESS_300_VALUE;
}
if (rState.getValue().getOptionalCodes().contains(125_CODE)
&& rState
.getValue()
.getOptionalCodes()
.contains(600_CODE)) {
throw new ServiceException("Multiple options received");
}
if (rState.getValue().getOptionalCodes().contains(125_CODE)) {
return 125_VALUE;
} else if (rState
.getValue()
.getOptionalCodes()
.contains(600_CODE)) {
return 600_VALUE;
} else {
return 300_VALUE;
}
}
I thought I might be able to refactor it to something like public static String calculateAmount(QRequest ... qRequest, CState ... cState, RState ... rState) { then add some logic to the method to work out which type it is and proceed from there but that doesn't work.
An option which would work would be to refactor my calculateAmount() to accept a Value object and have 3 new methods, one which will accept each parameter type and extract the Value object.
Is it possible to refactor this so there's only one method which will accept any one of the 3 parameter types?
Expanding on my comment, I'd suggest the following options:
Introduce an interface
This allows you to write code which knows that whatever you pass is of type HasValue and thus has a getValue() method.
interface HasValue {
ValueType getValue();
}
class QRequest implements HasValue { ... }
class CState implements HasValue { ... }
class RState implements HasValue { ... }
public static String calculateAmount(HasValue hasValue) {
ValueType value = hasValue.getValue();
if ( value == null) {
return 300_VALUE;
}
if ( value.getOptionalCodes().contains(125_CODE)
&& value.getOptionalCodes().contains(600_CODE)) {
throw new ServiceException("Multiple options received");
}
if (value.getOptionalCodes().contains(125_CODE)) {
return 125_VALUE;
} else if (value.getOptionalCodes().contains(600_CODE)) {
return 600_VALUE;
} else {
return 300_VALUE;
}
}
Introduce a helper method
If you can't introduce a common interface for some reason you need to provide the overloads for each type. However, if their getValue() methods all return the same type (ValueType is a placeholder for it) then a helper method that just gets the value and operates on that.
public static String calculateAmount(QRequest qRequest) {
return calculateAmountHelper(qRequest.getValue());
}
public static String calculateAmount(CState cState) {
return calculateAmountHelper(cState.getValue());
}
public static String calculateAmount(RState rState) {
return calculateAmountHelper(rState.getValue());
}
//or make it public and call this instead of the other 3 methods
private static String calculateAmountHelper(ValueType value) {
if ( value == null) {
return 300_VALUE;
}
if ( value.getOptionalCodes().contains(125_CODE)
&& value.getOptionalCodes().contains(600_CODE)) {
throw new ServiceException("Multiple options received");
}
if (value.getOptionalCodes().contains(125_CODE)) {
return 125_VALUE;
} else if (value.getOptionalCodes().contains(600_CODE)) {
return 600_VALUE;
} else {
return 300_VALUE;
}
}
i've a rather complex problem. I'am currently developing a a little groovy based script language for an ERP System. The functions and syntax of "my" script language are based on the already existing old FO language which is used by the erp system.
Therefore: I'am getting values from the ERP with calls like h.fieldname, where h the currently selected dataset is and fieldname the name of the field I want my field value from.
I get the field value e.g. of type String. What I now want is to extend these strings I retrieve with a few functions, which are based on the "old" syntax.
// some samples
// get last 3 characters
h.fieldname >> 3
// get first 4 characters
h.fieldname << 4
// should still work even if h.fieldname, returns something which extends String but is not a String
assert h.fieldname == "Foo"
UPDATE
I tried to make use of the answer of #daggett, here my approach:
public abstract class BaseScript extends Script implements GroovyObject {
#Override
public Object run() {
Object o = null;
try {
final ExpandoMetaClass metaClass = new ExpandoMetaClass(String.class, false, true);
//Closure c = { int x-> delegate[-x..-1] };
//ClosureMetaMethod foo = new ClosureMetaMethod​("rightShift ", c , doCall);
metaClass.initialize();
o = runCode();
} catch (Exception e) {
this.onerror(e);
} finally {
this.always();
}
return o;
}
public abstract Object runCode();
public Object always() {
return null;
}
public Object onerror(Object ex) {
if (ex instanceof Exception) {
Exception e = (Exception) ex;
e.printStackTrace();
}
return null;
}
}
But honestly i've no idea how to implement it and I also can't find any example.
UPDATE 2 and solution
Based on the answer of #daggett.
package groovy.runtime.metaclass.java.lang;
import groovy.lang.DelegatingMetaClass;
import groovy.lang.MetaClass;
public class StringMetaClass extends DelegatingMetaClass {
public StringMetaClass(Class<?> theClass) {
super(theClass);
}
public StringMetaClass(MetaClass metaClass) {
super(metaClass);
}
#Override
public Object invokeMethod(Object object, String name, Object[] args) {
// implementiert "test" >> 3
if (name.equals("rightShift")) {
if (args.length == 1) {
if (args[0] instanceof Integer) {
String str = object.toString();
int x = ((Integer) args[0]).intValue();
if (str.length() > x) {
return str.substring(str.length() - x);
}
return str;
} else {
throw new IllegalArgumentException("wrong argument type, should be integer");
}
} else {
throw new IllegalArgumentException("too many arguments");
}
}
// implementiert "test" << 3
if (name.equals("leftShift")) {
if (args.length == 1) {
if (args[0] instanceof Integer) {
String str = object.toString();
int x = ((Integer) args[0]).intValue();
if (str.length() > x) {
return str.substring(0,x);
}
return str;
} else {
throw new IllegalArgumentException("wrong argument type, should be integer");
}
} else {
throw new IllegalArgumentException("too many arguments");
}
}
else {
return super.invokeMethod(object, name, args);
}
}
}
you can't extend string class because it's final, however in groovy you can add new methods to string class with help of metaclass
String.metaClass.rightShift = { int x-> delegate[-x..-1] }
"1234567890" >> 3
returns
890
in the same way implement the method leftShift for <<
the last request (assert s1==s2) is not relevant because String is a final class (not extendable)
I have this code in Modula-2,
PROCEDURE Prune(typeExp: TypeExp): TypeExp;
BEGIN
CASE typeExp.^class OF
| VarType:
IF typeExp^.instance = NIL THEN
RETURN typeExp;
ELSE
typeExp^.instance = Prune(typeExp^.instance);
RETURN typeExp^.instance;
END;
| OperType: RETURN typeExp;
END;
END Prune;
I have several problems when I try to convert this code into java. I can create an instance and judge if its instance is null and then choose what to return. But I don't really know what to do with the case 2, which is the instance might be a new Opentype(); because only one value can be returned in this case.
public TypeExp Prune(TypeExp typeExp){
TypeExp r = new VarType();
if (r.instance == null) {
return r;
}
else {
r.instance = Prune(r.instance);
return r.instance;
}
}
The second issue is I don't think I can call the function Prune() inside itself, so what can I do? Thanks in advance.
I dont really know Modula-2, but it might be something like this:
public TypeExp Prune(TypeExp typeExp) {
if (typeExp instanceof VarType) {
if (typeExp.instance == null) {
return typeExp;
}
else {
typeExp.instance = Prune(typeExp.instance);
return typeExp.instance;
}
} else if (typeExp instanceof OperType) {
return typeExp;
}
//if typeExp is not an instance of VarType or OperType
return null;
}
The Modula code does not return in all code paths. Thats not possible in Java. I inserted return null in those cases. Thats probably wrong for your application though.
Below example not same as your func, but I think you can modify to your needs. It hides your return types behind Type class => you can return objects of two classes.
Main
package com.type;
public class Main {
public static void main(String[] args) {
Type first = new FirstType();
Type second = new SecondType();
System.out.println(func(first).getTypeName());
System.out.println(func(first).getTypeName());
System.out.println(func(second).getTypeName());
}
public static Type func(Type type) {
if(type instanceof FirstType) {
type.setTypeName("First");
} else {
type.setTypeName("Second");
// something here
}
return type;
}
}
Type
package com.type;
public class Type {
private String typeName;
public Type() {}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
FirstType
package com.type;
public class FirstType extends Type {
}
SecondType
package com.type;
public class SecondType extends Type {
}
I would like to call method(using reflection) which has parameter Interface - i.e: List but with implementation of List.
For example:
public class Test {
public static void main(String[] args) throws NoSuchMethodException {
Method method = Test1.class.getMethod("method", new Class[]{ArrayList.class});
}
public class Test1 {
public void method(List list) {
System.out.println("method");
}
}
}
I get NoSuchMethodException. In this case i know which params i get, problem is that I want to use this in general when i don't "statically" know param types.
Is possible that getMethod returns also method which has interface as parameter? Or i have to write my own "methodsearcher"
Thank you.
EDIT:
It's much more complicated. I'm trying to write something like "dynamic modular architecture" in my program. I have Core, which should comunicate with other modules. So i don't know params classes in programming time but in runtime.
public Object processMessage(String target, String methodName, List<Object> params, Object returnNonExist) {
Module m = modules.get(target);
if (m == null) {
return returnNonExist;
} else {
Class[] paramsTypes = new Class[params.size()];
for (int i = 0; i < params.size(); i++) {
paramsTypes[i] = params.get(i).getClass();
}
}
try {
Method method = m.getClass().getMethod(methodName, paramsTypes);
Object result = method.invoke(m, params.toArray());
return result;
}
Is it better?
I probably found solution - I have to write my own "method searcher" which respect interface implementation and superclases. It looks like this:
public static Method findMethod(Object m, String methodName, Class[] paramsTypes) {
Method[] metody = m.getClass().getDeclaredMethods();
List<Method> sameNames = new ArrayList<Method>();
// filter other names
for (Method meth : metody) {
if (meth.getName().equals(methodName)) {
sameNames.add(meth);
}
}
// lets find best candidate
if (sameNames.isEmpty()) {
return null;
} else {
// filter other count of parameters
List<Method> sameCountOfParameters = new ArrayList<Method>();
for (Method meth : sameNames) {
if (meth.getParameterTypes().length == paramsTypes.length) {
sameCountOfParameters.add(meth);
}
}
if (sameCountOfParameters.isEmpty()) {
return null;
} else {
for (Method meth : sameCountOfParameters) {
// first one, which is suitable is the best
Class<?>[] params = meth.getParameterTypes();
boolean good = true;
for (int i = 0; i < params.length && good; i++) {
if (params[i].isInterface() && Arrays.asList(paramsTypes[i].getInterfaces()).contains(params[i])) {
//if i-th paramater type is Interface and we search method with its implementation
good = true;
continue;
} else {
// if we call it with subclass and parameter typ is superclass
if (paramsTypes[i].getSuperclass().equals(params[i])) {
good = true;
continue;
}
}
good = false;
}
if (good) {
return meth;
}
}
}
}
return null;
}
I'am using this after standard getMethod throws "NoSuchMethodException" (It is in about 5% cases, so i don't care about speed.
You should use List class, not ArrayList.
Method method = Test1.class.getMethod("method", new Class[]{List.class});
Great answer from #radeczek. I extended it to work on subclasses ...
public Method findMethod(String name, Class<?>[] paramsTypes) {
Method[] methods = object.getClass().getMethods();
List<Method> sameNames = new ArrayList<Method>();
// filter other names
for (Method m : methods) {
if (m.getName().equals(name)) {
sameNames.add(m);
}
}
// lets find best candidate
if (sameNames.isEmpty()) {
return null;
} else {
// filter other count of parameters
List<Method> sameCountOfParameters = new ArrayList<Method>();
for (Method m : sameNames) {
if (m.getParameterTypes().length == paramsTypes.length) {
sameCountOfParameters.add(m);
}
}
if (sameCountOfParameters.isEmpty()) {
return null;
} else {
for (Method m : sameCountOfParameters) {
// first one, which is suitable is the best
Class<?>[] params = m.getParameterTypes();
boolean good = true;
for (int i = 0; i < params.length && good; i++) {
// Recurse into subclasses
good = findSubclass(paramsTypes[i],params[i]);
}
if (good) {
return m;
}
}
}
}
return null;
}
/**
* Recursive check for interfaces of superclasses.
*
* #param paramType
* #param param
* #return
*/
private boolean findSubclass(Class<?> paramType, Class<?> param) {
if (param.isInterface() && Arrays.asList(paramType.getInterfaces()).contains(param)) {
return true;
} else {
if (paramType.getSuperclass() != null) {
return findSubclass(paramType.getSuperclass(), param);
} else {
return false;
}
}
}
I have two objects of same type.
Class A {
String a;
List b;
int c;
}
A obj1 = new A();
A obj2 = new A();
obj1 => {a = "hello"; b = null; c = 10}
obj2 => {a = null; b = new ArrayList(); c = default value}
Can you please let me know what is the best way to combine this objects into single object?
obj3 = {a = "hello"; b = (same arraylist from obj2); c = 10}
This works as long as you have POJOs with their own getters and setters. The method updates obj with non-null values from update. It calls setParameter() on obj with the return value of getParameter() on update:
public void merge(Object obj, Object update){
if(!obj.getClass().isAssignableFrom(update.getClass())){
return;
}
Method[] methods = obj.getClass().getMethods();
for(Method fromMethod: methods){
if(fromMethod.getDeclaringClass().equals(obj.getClass())
&& fromMethod.getName().startsWith("get")){
String fromName = fromMethod.getName();
String toName = fromName.replace("get", "set");
try {
Method toMetod = obj.getClass().getMethod(toName, fromMethod.getReturnType());
Object value = fromMethod.invoke(update, (Object[])null);
if(value != null){
toMetod.invoke(obj, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am using Spring Framework. I was facing the same issue on a project.
To solve it i used the class BeanUtils and the above method,
public static void copyProperties(Object source, Object target)
This is an example,
public class Model1 {
private String propertyA;
private String propertyB;
public Model1() {
this.propertyA = "";
this.propertyB = "";
}
public String getPropertyA() {
return this.propertyA;
}
public void setPropertyA(String propertyA) {
this.propertyA = propertyA;
}
public String getPropertyB() {
return this.propertyB;
}
public void setPropertyB(String propertyB) {
this.propertyB = propertyB;
}
}
public class Model2 {
private String propertyA;
public Model2() {
this.propertyA = "";
}
public String getPropertyA() {
return this.propertyA;
}
public void setPropertyA(String propertyA) {
this.propertyA = propertyA;
}
}
public class JustATest {
public void makeATest() {
// Initalize one model per class.
Model1 model1 = new Model1();
model1.setPropertyA("1a");
model1.setPropertyB("1b");
Model2 model2 = new Model2();
model2.setPropertyA("2a");
// Merge properties using BeanUtils class.
BeanUtils.copyProperties(model2, model1);
// The output.
System.out.println("Model1.propertyA:" + model1.getPropertyA(); //=> 2a
System.out.println("Model1.propertyB:" + model1.getPropertyB(); //=> 1b
}
}
Maybe something like
class A {
String a;
List<..> b;
int c;
public void merge(A other) {
this.a = other.a == null ? this.a : other.a;
this.b.addAll(other.b);
this.c = other.c == 0 ? this.c : other.c;
}
}
A a1 = new A();
A a2 = new A();
a1.a = "a prop";
a2.c = 34;
a1.merge(a2);
A.merge might return a new A object instead of modifing current.
Just accommodating boolean sync. and case sensitive(camel notation)
public boolean merge(Object obj){
if(this.equals(obj)){
return false;
}
if(!obj.getClass().isAssignableFrom(this.getClass())){
return false;
}
Method[] methods = obj.getClass().getMethods();
for(Method fromMethod: methods){
if(fromMethod.getDeclaringClass().equals(obj.getClass())
&& (fromMethod.getName().matches("^get[A-Z].*$")||fromMethod.getName().matches("^is[A-Z].*$"))){
String fromName = fromMethod.getName();
String toName ;
if(fromName.matches("^get[A-Z].*")){
toName = fromName.replace("get", "set");
}else{
toName = fromName.replace("is", "set");
}
try {
Method toMetod = obj.getClass().getMethod(toName, fromMethod.getReturnType());
Object value = fromMethod.invoke(this, (Object[])null);
if(value != null){
toMetod.invoke(obj, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
If you create getters and setters for the attributes, you can use the copyProperties method from Commons BeanUtils.
Add this method to your POJO, then use it like myObject.merge(newObject). It uses generics to loop through your POJO's fields, so you don't mention any field names:
/**
* Fill current object fields with new object values, ignoring new NULLs. Old values are overwritten.
*
* #param newObject Same type object with new values.
*/
public void merge(Object newObject) {
assert this.getClass().getName().equals(newObject.getClass().getName());
for (Field field : this.getClass().getDeclaredFields()) {
for (Field newField : newObject.getClass().getDeclaredFields()) {
if (field.getName().equals(newField.getName())) {
try {
field.set(
this,
newField.get(newObject) == null
? field.get(this)
: newField.get(newObject));
} catch (IllegalAccessException ignore) {
// Field update exception on final modifier and other cases.
}
}
}
}
}
There is a dynamic solution to merge any two objects which require Reflection and Recursion.
public <T> T merge(T local, T remote, ArrayList<String> listOfClass)
throws IllegalAccessException, InstantiationException {
Class<?> clazz = local.getClass();
Object merged = clazz.newInstance();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
Object localValue = field.get(local);
Object remoteValue = field.get(remote);
if (localValue != null) {
if (listOfClass.contains(localValue.getClass().getSimpleName())) {
field.set(merged, this.merge(localValue, remoteValue, listOfClass));
} else {
field.set(merged, (remoteValue != null) ? remoteValue : localValue);
}
} else if (remoteValue != null) {
field.set(merged, remoteValue);
}
}
return (T) merged;
}
Variable Description:
local: The object on to which the other will be merged
remote: The object which will be merged to the local object
listOfClass: The ArrayList of custom classes in the given object
The function returns a merged object which is good to go.
Kudos! :)
In your very special case it looks like you want a new object that takes the real values from both instances. Here is an implementation that will do that. The method should be add to class A so that it can access the fields.
public A specialMergeWith(A other) {
A result = new A();
result.a = (a == null ? other.a : a);
result.b = (b == null ? other.b : b);
result.c = (c == DEFAULT_VALUE ? other.c : c);
return result;
}
public static Object mergeObjects(Object source, Object target) throws Exception {
Field[] allFields = source.getClass().getDeclaredFields();
for (Field field : allFields) {
if(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())){
continue;
}
if (!field.isAccessible() && Modifier.isPrivate(field.getModifiers()))
field.setAccessible(true);
if (field.get(source) != null) {
field.set(target, field.get(source));
}
}
return target;
}
Using java reflection, support only for the same class.