java


Creating object from class located inside JAR? [duplicate]


I am trying to make a Java tool that will scan the structure of a Java application and provide some meaningful information. To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder) and use reflection to read about their methods. This is proving to be near impossible.
I can find a lot of solutions based on URLClassloader that allow me to load specific classes from a directory/archive, but none that will allow me to load classes without having any information about the class name or package structure.
EDIT:
I think I phrased this poorly. My issue is not that I can't get all of the class files, I can do that with recursion etc. and locate them properly. My issue is obtaining a Class object for each class file.
The following code loads all classes from a JAR file. It does not need to know anything about the classes. The names of the classes are extracted from the JarEntry.
JarFile jarFile = new JarFile(pathToJar);
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = { new URL("jar:file:" + pathToJar+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
// -6 because of .class
String className = je.getName().substring(0,je.getName().length()-6);
className = className.replace('/', '.');
Class c = cl.loadClass(className);
}
edit:
As suggested in the comments above, javassist would also be a possibility.
Initialize a ClassPool somewhere before the while loop form the code above, and instead of loading the class with the class loader, you could create a CtClass object:
ClassPool cp = ClassPool.getDefault();
...
CtClass ctClass = cp.get(className);
From the ctClass, you can get all methods, fields, nested classes, ....
Take a look at the javassist api:
http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/html/index.html
List All the classes inside jar file.
public static List getClasseNames(String jarName) {
ArrayList classes = new ArrayList();
if (debug)
System.out.println("Jar " + jarName );
try {
JarInputStream jarFile = new JarInputStream(new FileInputStream(
jarName));
JarEntry jarEntry;
while (true) {
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null) {
break;
}
if (jarEntry.getName().endsWith(".class")) {
if (debug)
System.out.println("Found "
+ jarEntry.getName().replaceAll("/", "\\."));
classes.add(jarEntry.getName().replaceAll("/", "\\."));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return classes;
}
To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder)
Scanning all of the files in a folder is simple. One option is to call File.listFiles() on the File that denotes the folder, then iterate the resulting array. To traverse trees of nested folders, use recursion.
Scanning the files of a JAR file can be done using the JarFile API ... and you don't need to recurse to traverse nested "folders".
Neither of these is particularly complicated. Just read the javadoc and start coding.

Related Links

Apache POI. XWPFRun: fontFamily not updated
JavaFX AnchorPane is not working
Java Generics: Special usage <T extends Object & Interface>
how to fix Root type mapping not empty after parsing! error in Elasticsearch to create dynamic mapping
Hibernate bean mappings for joining 3 tables
Array Index out of bounds exception:Android
Java reverse the order of accessing a list in a for loop
Java ArrayIndexOutOfBoundsException when reading user input [duplicate]
How to remove text between <script></script> tags
Better solution than while (reentrantLock.isLocked()) for waiting
jersey 2 multipart pojo is always null
Spring JPA Inconsistent Responses
migration apache commons cookiePolicy to cookieSpec of httpClient4.3
Error occurred during initialization of VM java/lang/NoClassDefFoundError: java/lang/Object in Redhat
Spring configuration with filter chain
Bitwise operators and for loop

Categories

HOME
testing
multithreading
cloud
magnific-popup
heroku
include
ckeditor
baqend
in-app-purchase
midi
izpack
imacros
circular-dependency
leiningen
percona
clearcase-ucm
vaadin7
angular-ui
pugjs
propel
dxf
firebase-crash-reporting
microsoft-sync-framework
fgetcsv
web-api-testing
msys2
delicious-api
madlib
fabric8
catel
typed.js
lxd
subset-sum
cloud-code
amazon-kinesis-kpl
ios5
gesture
libvpx
webdriver-manager
awt
texmaker
janrain
qwt
fault
scrollable
chain-builder
zip4j
pebble-watch
r-forge
mediaelement
time-and-attendance
setuptools
ctest
plottable.js
holder.js
disque
essence
whois
bluemix-app-scan
suffix-tree
revolution-r
uid
historian
javax.sound.midi
spim
spidermonkey
riak-cs
proj4js
sorl-thumbnail
block-device
winddk
rdtsc
nsbutton
rdl
eol
fluentautomation
mechanize-ruby
dealloc
hyprlinkr
srs
floating-point-precision
cdc
tws
ocunit
delphi-6
simba
quickdialog
dice
objective-c-2.0
dbproviderfactories
wse3.0
yetanotherforum
krl
disclosure
actionview
imac
mysql-error-1005
subviews
h.323
forums
compiler-specific
firefox4
eqatec
zend-decorators
ugc

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App