| 1 |
|
package org.doxla.spring.resource.util; |
| 2 |
|
|
| 3 |
|
import java.io.IOException; |
| 4 |
|
|
| 5 |
|
import org.springframework.core.io.Resource; |
| 6 |
|
import org.springframework.util.Assert; |
| 7 |
|
import org.springframework.util.StringUtils; |
| 8 |
|
|
| 9 |
|
public class ResouceToClassUtil { |
| 10 |
|
|
| 11 |
|
private static final String JAR_RESOURCE_PREFIX = "jar!"; |
| 12 |
|
|
| 13 |
|
|
| 14 |
|
|
| 15 |
|
|
| 16 |
0 |
private ResouceToClassUtil(){} |
| 17 |
|
|
| 18 |
|
public static final Class resolveClassFromJarResouce(Resource resource) throws ClassNotFoundException{ |
| 19 |
|
|
| 20 |
19 |
Assert.isTrue(resource.exists(),"Resource didn't exist ["+resource.toString()+"]"); |
| 21 |
|
String resourcePath; |
| 22 |
|
try { |
| 23 |
19 |
resourcePath = resource.getURL().getPath(); |
| 24 |
0 |
} catch (IOException e) { |
| 25 |
|
|
| 26 |
0 |
throw new RuntimeException(e); |
| 27 |
19 |
} |
| 28 |
19 |
int jarIndex = resourcePath.indexOf(JAR_RESOURCE_PREFIX); |
| 29 |
19 |
Assert.isTrue(jarIndex > 0,"Resource is not inside a jar"); |
| 30 |
|
|
| 31 |
|
|
| 32 |
19 |
resourcePath = resourcePath.substring(jarIndex + JAR_RESOURCE_PREFIX.length() + 1); |
| 33 |
19 |
resourcePath = resourcePath.replaceAll("\\.class", ""); |
| 34 |
|
|
| 35 |
19 |
String className = resourcePath.replaceAll(getDirectorySeparatorPattern(resourcePath),"."); |
| 36 |
19 |
Assert.isTrue(StringUtils.hasLength(className),"couldn't resolve classname from String "+resourcePath); |
| 37 |
|
|
| 38 |
19 |
Class clazz = Class.forName(className); |
| 39 |
|
|
| 40 |
19 |
return clazz; |
| 41 |
|
} |
| 42 |
|
|
| 43 |
|
|
| 44 |
|
private static final String getDirectorySeparatorPattern(String path) { |
| 45 |
19 |
if(path.contains("/")) return "/"; |
| 46 |
0 |
else return "\\\\"; |
| 47 |
|
} |
| 48 |
|
|
| 49 |
|
|
| 50 |
|
|
| 51 |
|
} |