'Create a generic method with generic signature

i have some redundant code that i would like to remove, my goal would be to create a method of this kind:

private GenericClass myMethod(GenericClass genericClass){
    genericClass.getTipe(); //tipe1 or tipe2
    genericClass.setValue("foo");
    genericClass.setValue2("foo");
    //some logic
    return genericClass;

}

Where this method can pass two similar classes but which differ in the type of an attribute

public class Class1{
   private Tipe1 tipe1;
   private String value; 
   private String value2;
   //Constructor,Getter and Setter
}

public class Class2{
   private Tipe2 tipe2;
   private String value; 
   private String value2;
   //Constructor,Getter and Setter
}

What I would like to do is call the method

someServiceIml.myMethod ("Foo")

passing either an object of type Class1 or Class2 according to my needs, the business logic behind myMethod is practically the same.

This method i wish it was in the same implementation of a certain service, could you give me some solution?



Solution 1:[1]

public class MyClass {
    public static void main(String args[]) {
      
        Class1 c1 = new Class1();
        
        Class2 c2 = new Class2();

        GenericClass gc = myMethod(c1);
        
        System.out.println(gc);
    }
    
    private static GenericClass myMethod(GenericClass genericClass){
        genericClass.getTipe(); //tipe1 or tipe2
        genericClass.setValue("foo");
        genericClass.setValue2("foo");
        //some logic
        return genericClass;
    }
}

class Class1 extends GenericClass<Tipe1>{

}

class Class2 extends GenericClass<Tipe2>{

}

class Tipe1 {
    
}
class Tipe2 {
    
}

class GenericClass<T> implements Tipe<T> {
    private String value;
    private String value2;
    private T t;
    
    public T getTipe() {
        return t;
    }
    
    void setValue(String s) {
        value = s;
    }
    void setValue2(String s) {
        value2 = s;
    }
}

interface Tipe<T> {
    public T getTipe();
}

or you can cast to parent class like:

GenericClass gc = new Class2();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yasin Uyar