I am trying to use Java reflection to read class files and output its contents. Here is my Reflect.java file code that throws the error:
String className = classNames.get(classNum).replace(".class", "");
String packageAndClassName = packageName + "." + className;
System.out.println(packageAndClassName);
try{
Class<?> c = Class.forName(packageAndClassName);
My command to read a package's contents looks like this
java -classpath . reflect.Reflect package /u/username/Desktop/Experiment/others/package/
Here, arg[0]= package and arg[1]=/u/username/Desktop/Experiment/others/package/
My classpath looks like so:
/u/username/Desktop/Experiment/reflect/:/u/username/Desktop/Experiment/others/package/
"others" contains the package. I have no idea what I am doing wrong. I have looked up a lot of answers and they involve typing in the whole name of the Reflect class, which I am doing in my command. Any ideas as to what I'm missing?
You should pay attention to the classpath parameter. I'm guessing the class you are trying to load is not in the path so you need to add the package directory there.
The other option is to use the UrlClassLoader
Related
This question already has answers here:
Find where java class is loaded from
(12 answers)
Closed 9 years ago.
Is there a way to get the path of main class of the running java program.
structure is
D:/
|---Project
|------bin
|------src
I want to get the path as D:\Project\bin\.
I tried System.getProperty("java.class.path"); but the problem is, if I run like
java -classpath D:\Project\bin;D:\Project\src\ Main
Output
Getting : D:\Project\bin;D:\Project\src\
Want : D:\Project\bin
Is there any way to do this?
===== EDIT =====
Got the solution here
Solution 1 (By Jon Skeet)
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
This printed out:
file:/C:/Users/Jon/Test/foo/Test.class
Solution 2 (By Erickson)
URL main = Main.class.getResource("Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol()))
throw new IllegalStateException("Main class is not stored in a file.");
File path = new File(main.getPath());
Note that most class files are assembled into JAR files so this won't work in every case (hence the IllegalStateException). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to getResourceAsStream() in place of getResource(), and that will work whether the class is on the file system or in a JAR.
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
Try this code:
final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
replace 'MyClass' with your class containing the main method.
Alternatively you can also use
System.getProperty("java.class.path")
Above mentioned System property provides
Path used to find directories and JAR archives containing class files.
Elements of the class path are separated by a platform-specific
character specified in the path.separator property.
You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
I am having a little issue trying to figure out the best solution to the my path problems. I am running a java test that I want to get two things.
The absolute location of the project
The absolute location to the current class file that is running
I want to proper / or \ being on the OS version so the folder structure stays intact. I am currently using this but it is not exactly what I am looking for
final String parentDir = System.getProperty("user.dir");
final String path = "src/test/java/" + method.getDeclaringClass()
.getCanonicalName().replaceAll("\\.", "/") + ".java";
Any help would be appreciated. Thanks
Update: I am trying to get the url of the precompiled code as I need access to the comments in the code. This may change some of your guys answers
Update 2: Ok I got it to work.
final String path = new File(getClass().getResource("/").getFile())
.getParent().split("target")[0] + "src/test/java/" + method
.getDeclaringClass().getCanonicalName()
.replaceAll("\\.", "/") + ".java";
Thanks Guys
Given that you are calling this from MyClass you should call
File directory = (new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())).getParentFile();
I had the same question once. In addition to Jatin's answer I had to add an toURI() to get the correct path on all platforms (Windows, etc.) and post 1.5 JVMs.
If say you are running from jar file:
new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent()+"/"
returns the folder containing the jar file.
Remove the .getParent() above to get path to the exact class file
I have searched for hours and I am not finding a solution, this is my last resort
I have a program that creates a data file via serialization, and the file is created successfully, and I can read the data (Deserialization) using the same program/ package.
The problem I have is that the data file must be read from another program and I have created the same class but I cannot read from the file (Class not found error) from a different program
//Class
public static class
{
File inst_path = ....
}
So I created an external class so that I can create the data file from the same class and read using the same class. The class is saved as a jar file
How can I link both programs to the same class (External File)
Edit
Currently I am accessing my local these way
records.classes myclass = new records.classes()
myclass.inst_path = new File...
So I am looking for something that will look something like ...
externaljar.jar.classes myclass = new ...
I know this won't work but I need something like it.
You just need the jar to be in the classpath of the two programs. Then you use the class as any other class: by importing it and using its name:
java -cp jarWithCommonSerializedClass.jar;jarWithTheProgramClasses.jar the.program.MainClass
Note: this is for Windows. Under *nix, : must be used instead of ;.
See http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html.
Also, respect the Java naming conventions. Java classes start with an upper-case letter. Variables never contain underscores and are camelCased.
I would like to generate some basic html interface documentation (without comments of course) of the class files within a jar to which I do not have source. How can I go about doing this?
The old tool of classdoc [Class Doc][1]http://classdoc.sourceforge.net/ which was available for java 1.3 used to provide this service. It seems to me that this can be done via the use of reflection.
Any ideas or examples using javadoc or another utility on how to perform this seemingly simple task on 1.6 or 1.7 classes?
There are maybe automated solutions but I do not know any. My best bet would be to write manually some code which will generate dummy java files with javadoc inside. You'll have to browse the jar file using something like this:
ArrayList<Class> classes = new ArrayList<Class>();
JarFile jfile = new JarFile("your jar file name");
String pkgpath = pckgname.replace(".", "/");
for (Enumeration<JarEntry> entries = jfile.entries(); entries.hasMoreElements();) {
JarEntry element = entries.nextElement();
if(element.getName().startsWith(pkgpath)
&& element.getName().endsWith(".class")){
String fileName = element.getName().substring(pckgname.length() + 1);
classes.add(Class.forName(pckgname + "." + fileName .split("\\.")[0]));
}
}
Then for each class you'll have to browse their methods to finally write down the dummy classes which look like the original ones in the jar file. While the code write the dummy methods to file, make it also write javadoc comments based on what the parameters and the return type are.
Once this is done use javadoc to generate the documentation from your dummy classes.
This might be a bit long to do but that's my guess for this one...
You can use jar tvf yourjar.jar for listing the classes, and javap for disassembling the classes, it yields a very legible documentation.
I am trying to load a directory from a properties file. I have the following defined in the property file:
image.src.dir = "C:\\Temp\\foo\\"
Yes, the directory name is like that ... with mixed case. I have also tried simply referring to the directory as "/Temp/foo" with the same outcome.
I have the following code which fails despite the directory existing.
String srcDir = prop.getProperty("image.src.dir");
File folder = new File(srcDir);
if (!folder.isDirectory()) {
System.err.println("Directory: " + srcDir + " doesn't exist");
}
Thanks for the hint ...
The problem & solution:
solution: image.src.dir=C:\\Temp\\foo\\
problem: image.src.dir = "C:\\Temp\\foo\\"
That was my problem ..!
You have quotes in your property file. Quotes are needed for literal Strings in Java, but not Strings defined inside of a properties file.
Try this:
image.src.dir = C:\\Temp\\foo\\
Did you try to System.println(srcDir) if the string gets properly loaded from the properties file? Is the directory accessible (are the rights for superdirectories correct?).