问题
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());
}
回答1:
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.
回答2:
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.
回答3:
I think the OP is trying to identify a file on the classpath in which the class file exists. See http://asolntsev.blogspot.com/2008/03/how-to-find-which-jar-file-contains.html
回答4:
Take a look at RMI (Remote Method Invocation).
来源:https://stackoverflow.com/questions/1768256/java-class-file-and-java-lang-class