Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: .class file and java.lang.Class

Is java.lang.Class the same as the actual .class file? i.e. is the content equivalent?

I want to send the .class over socket, and was wondering if instead of trying to find and load the actual .class file, if I could just transmit the java.lang.Class instead?

Elaboration (read if you want more info)

Suppose I have a Java class called SomeObj. When this file is compiled, a file called SomeObj.class will be generated.

We also know that if I have SomeObj as a type, we could get its java.lang.Class type by doing:

Class someObjClss = SomeObj.class;

We know java.lang.Class implements Serializable, thus it can be transmitted.

So is java.lang.Class basically the object representation of the actual .class file?

UPDATE:

Assuming I have transmitted the .class file over to another host, do I just use the defineClass() method to construct the class back?

Link here

UPDATE2:

This code does returns null InputStream. How is that possible?

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());
}
like image 834
sivabudh Avatar asked Mar 01 '23 00:03

sivabudh


2 Answers

No. java.lang.Class is a java class. It has its own .class file :-) An instance of java.lang.Class is used to represent class of your object allowing you to perform certain operations (e.g. use reflection API) on it.

Serialization has nothing to do with .class file at all - it's object state that gets serialized. If you were to serialize Class<MyObject> and send that over the wire to a JVM which does not have MyObject.class, it still wouldn't know what MyObject is.

Why do you need to manually send .class over the wire to begin with? There are remote class loaders to deal with this.

like image 133
ChssPly76 Avatar answered Mar 05 '23 16:03

ChssPly76


A java.lang.Class instance is related to a corresponding ".class" file, but they are by no means equivalent.

The java.lang.Class instance encodes the type signature for a ".class" file, but not a lot more. So, though a java.lang.Class can be serialized, doing so does not provide you with enough to allow an instance of the corresponding class to be instantiated at the other end. If you want to do that, you should be sending the ".class" file.

like image 36
Stephen C Avatar answered Mar 05 '23 15:03

Stephen C