Skip to content

Commit

Permalink
two utilities added
Browse files Browse the repository at this point in the history
  • Loading branch information
igr committed Sep 3, 2017
1 parent ddc7cfc commit 27f067e
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions jodd-core/src/main/java/jodd/util/ClassUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

import jodd.util.cl.ClassLoaderStrategy;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
Expand All @@ -41,6 +43,7 @@
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
Expand All @@ -50,6 +53,7 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarFile;

/**
* Class utilities.
Expand Down Expand Up @@ -1250,4 +1254,67 @@ public static Class findEnum(Class target) {
return null;
}


// ---------------------------------------------------------------- misc

/**
* Returns the class of the immediate subclass of the given parent class for
* the given object instance; or null if such immediate subclass cannot be
* uniquely identified for the given object instance.
*/
public static Class<?> childClassOf(Class<?> parentClass, Object instance) {

if (instance == null || instance == Object.class) {
return null;
}

if (parentClass != null) {
if (parentClass.isInterface()) {
return null;
}
}

Class<?> childClass = instance.getClass();
while (true) {
Class<?> parent = childClass.getSuperclass();
if (parent == parentClass) {
return childClass;
}
if (parent == null) {
return null;
}
childClass = parent;
}
}

/**
* Returns the jar file from which the given class is loaded; or null
* if no such jar file can be located.
*/
public static JarFile jarFileOf(Class<?> klass) {
URL url = klass.getResource(
"/" + klass.getName().replace('.', '/') + ".class");

if (url == null) {
return null;
}

String s = url.getFile();
int beginIndex = s.indexOf("file:") + "file:".length();
int endIndex = s.indexOf(".jar!");
if (endIndex == -1) {
return null;
}

endIndex += ".jar".length();
String f = s.substring(beginIndex, endIndex);
File file = new File(f);

try {
return file.exists() ? new JarFile(file) : null;
} catch (IOException e) {
throw new IllegalStateException(e);
}
}

}

0 comments on commit 27f067e

Please sign in to comment.