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

s ParseUser.CurrentUser() different on Parses servers from Client Side
Java Swing - button image Drag&Drop - showing image while moving
apache ReverseProxy configuration (apache web server url is changed to jboss server's url)
how to autoincreament id value in jpa annotations with oracle db ? how to generate uuid values?
What happening in Object.hashCode() method?
Getting java.security.AccessControlException on on calling getWidth() method of java.awt.image.RenderedImage class
How to store java Calendar time in MySql timestamp?
Is there a reason to call obj.getClass() while ignoring the return value?
Generate Random Numbers By Adding 0 Infront SELENIUM
How do I utilize supportsNullCreation() in Jersey?
How to remove a key from HashMap? [duplicate]
Split command does not function with Scanner
Error: cannot find symbol symbol: variable mes location: class ventasArreglo
Jsoup returning &nbsp for active text fields
Process 'command usr/lib/jvm/java-8-oracle/bin/java' finished with non-zero exit value 2
Serializable JPA entity with collection member

Categories

HOME
testing
testng
urbancode
google-api-php-client
layout
stock
vmware
framework7
gis
blueprintjs
etl
pc
windows-7-x64
footer
apache-metamodel
google-cloud-speech
django-cms
plunker
reverse-proxy
cx-freeze
bootstrap-tour
intel-pin
kannel
phpfox
greendao
fifo
madlib
webtest
avcapturesession
uiswipegesturerecognizer
atl
bower-install
host
retina-display
streamsets
twitch
broadcastreceiver
pdf-reactor
eclipse-gef
qwt
jlink
domain-model
integrity
snmptrapd
phishing
xml-attribute
flash-cs5
sigabrt
skype4py
hexdump
two-factor-authentication
unity-networking
rgeo
embedded-code
sysinternals
createprocessasuser
processmodel
mmc
python-green
gwidgets
android-nested-fragment
onactivityresult
heisenbug
kgdb
imdbpy
dbconnection
jplaton
spring-validator
lcs
venn-diagram
deobfuscation
mod-auth
f#-powerpack
servicehost
xfbml
yslow
digest-authentication
gallio
anti-piracy

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App