Unique identification of a Java class implementation

I've dealt with poorly forked projects that left me with dependencies that include multiple classes with exactly the same fully qualified name. Hence, I am getting AbstractMethodError

to call methods in the wrong implementations. My solution was to rename the class packages, which worked great.

However, now I am wondering if there is a better way - can we uniquely identify the implementation of a Java class?

+3


source to share


4 answers


You can check if two classes (or classes of two objects) are identical:

o1.getClass() == o2.getClass()

      



This expression is true

accurate when the classes are identical (i.e. loaded by the same classloader).

AFAIK there is no way to determine if a class is generated at runtime from a specific file.

0


source


You can check OSGI as a solution. You can specify dependencies between modules and load the exact class for each module



0


source


Classes are equal if they have the same fully qualified name and are loaded by the same classloader. So if you have different classloaders (and each classloader only knows one of the implementations, for example in an OSGi environment), you could theoretically identify them by checking their respective classloader.

Generally, however, having multiple classes with the same fully qualified name is a problem, and there is no other solution you would like to implement if you can rename packages. There may be special cases, but you must have very good reasons.

0


source


There is something called "ImplementationVersion" that you can access with, for example:

public class TestClassVersion {

public static void main(String[] args) {
    System.out.println("TestClassVersion: " + TestClassVersion.class.getPackage().getImplementationVersion());
    System.out.println("String: " + String.class.getPackage().getImplementationVersion());
    System.out.println("org.apache.commons.logging.Log: " + org.apache.commons.logging.Log.class.getPackage().getImplementationVersion());
}

      

}

Output:

TestClassVersion: null
String: 1.8.0_45
org.apache.commons.logging.Log: 1.0.4

      

The disadvantage of this is that you need to set this version to META-INF\MANIFEST.MF

-File (there it is s called

Implementation-version`) in Compile-Time - if you don't specify it, it will be zero,

Cm:

https://docs.oracle.com/javase/tutorial/deployment/jar/packageman.html

http://docs.oracle.com/javase/8/docs/api/java/lang/Package.html

0


source







All Articles