简体   繁体   中英

Is it possible to write a generic code using classes with same name from two different jars / packages

I am using two different versions of a dependency. Let's call them jar1 and jar2. These two dependencies have same structure and name of the classes that I intend to use. But I am having to write the same function twice as shown below.

public class App {

    A getA(B b, C c) {
        // do some processing with b and c
        return new A();
    }

    org.example.jar2.A getA(org.example.jar2.B b, org.example.jar2.C c) {
        // do some processing with b and c
        return new org.example.jar2.A();
    }


    public static void main(String[] args) throws Exception {

    }
}

Is there any way, either java generics or other, by which I will not have to write the same function twice because they are operating on classes from two different jars. Is it possible to write just one method for the below mentioned use case. The attributes that I am interested in from classes B and C are also the same in both the jars.

The simplest answer is you should not have 2 versions of same jar at class path, this might cause a lot of troubles and tools like gradle or maven will choose only one of jar version anyway. Usually when there is dependency upgrade from version 1 to version 2 you must keep in mind that changes should be backward compatible which means that version 2 can handle all cases of version 1. As you described it this is your case since they both behave exactly the same.

But if these jars are not the same and they are simply 2 different jars that shares some commons classes that you must handle then I would do:

Create internal representation of class Internal_A, Internal_B, Internal_C. When message arrive either in form of jar1 or jar2 you should create internal class objects and use them in function you have created. Additional logic to map jar1.A/B/C and jar2.A/B/C classes to internal representation is required but this is the simplest way.

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