Java: how is it that null?

This code returns a null InputStream as well as a null URL. Why is this? I have my own class, which I want to receive in the .class file as InputStream for serialization in 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()); } 
+3
source share
2 answers

First, you need a class loader. Secondly, you need to replace the dots . to the class name with forward slashes / and the suffix of the .class extension to identify the real path.

So this 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 had to add, inputStream.available() not a way to find out the file size. It simply returns the number of bytes that can be read without blocking. In other words, the return value should never be considered consistent. If you want to get the actual length, you really need to read the entire stream.

+3
source

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

Secondly, getName() will include the package, and a call to Class.getResource() will assume that the path belongs to the class if it does not start with a slash.

You need to replace '. in the class name with a slash and precede the slash for getResource() to work correctly.

If you can get the .class files as a resource, you will also need to add ".class" to the class name when calling getResource()

0
source

All Articles