简体   繁体   中英

Java passing generic objects

I have different objects(Object A and object B). But some of the objects' fields are same. I can't change the object classes( i mean i cant write a implement/extends condition for them ). I want to pass the objects to a method which uses the objects' fields They have same fields. I don't want to overloading. Which design is the most suitable for this?.

A obj1 = new A();
B obj2 = new B();

update(obj1);
update(obj2);

// my function
public <T extends myInterface> void update(T obj)
{
    obj.field+=1;
}

public interface myInterface{
   int field=0;
}

--------------
public class A{
   int field;
   .... // smt else
}
--------------
public class B{
   int field;
   .... // smt else
}

If you have two classes which do not implement a common interface or share a common base class, you can't really pass them to your function.

The fact that they have a common field doesn't matter.

You have 3 workarounds, none of which is really good:

  1. Have your function accept Object type, and check its type (A or B) inside using instanceof . This is ugly and not recommended as any class can be passed inside, and also your code has to check it's type all the time.
  2. Have your function accept Object type, Use reflection to access field with specific name, in this way:

    Field field = obj.getClass().getDeclaredField('myfeild'); Object value = field.get(obj);

This is better in that your code doesn't have to check types, but more unsafe. Any class can be passed to your function, and there's some dark magic which relies on static field names. If field name changes, your code breaks.

  1. Perhaps the best - Implement a wrapper for your objects. It will have two constructors, one for class A and one for class B. The wrapper will remember which kind of object resides inside. In its getField function if will have a single if statement. Have your function accept the wrapper type as the argument.

instanceof can be used indentify class of object. Like this:

public <T extends myInterface> void update(Object obj)
    {
        if ( obj instanceof A )
        {
            A a = (A)obj;
            a.field+=1;
        }
        if( obj instanceof B )
        {
            B b = (B)obj;
            b.field+=1;
        }
    }

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