tags:

views:

149

answers:

2

This code does returns null InputStream as well as null URL. Why is that? I have my own class that I want to get the actual .class file as an InputStream to serialize to bytes[].

Class clazz = String.class;

String className = clazz.getName(); System.out.println(className);
URL url = clazz.getResource(className);
if( url != null )
{
  String pathName = url.getPath(); System.out.println(className);
}

InputStream inputStream = clazz.getResourceAsStream(className);
if(inputStream != null )
{
  System.out.println(inputStream.available());
}
A: 

First off, I'm not sure if you can get the actual .class file as a resource.

Secondly getName() will include the package and calling Class.getResource will assume the path is relative to the class if it does not start with a slash.

You need to replace the '.'s in the class name with slashes and prepend a slash for getResource to work correctly.

If you can get .class files as a resource you'd also need to append '.class' to the class name when calling getResource()

cheers

Lee

leebutts
+2  A: 

Firstly, you need the context's classloader. Secondly, you need to replace the dots . in classname by forward slashes / and suffix the .class extension to identify the real path.

So this one should work:

String name = String.class.getName().replace(".", "/") + ".class";
URL url = Thread.currentThread().getContextClassLoader().getResource(name);
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);

Edit: I should have added, inputStream.available() is not the way to learn about the file size. It just returns the amount of bytes which are available to read without blocking. With other words, the return value should never be treated as consistent. If you want to get the actual length, you'll really need to read the entire stream.

BalusC
Copied, pasted, tested --> works! Three words: You are awesome. Thanks!
ShaChris23
Oh thank you for telling me about the available() too! I thought available() was the size of the .class file. Thanks again for your details!
ShaChris23
+1, though a simpler way (which I meant to write in the other question but messed up) is to use `clazz.getResourceAsStream(clazz.getSimpleName() + ".class")`.
ChssPly76