Java:.class文件和java.lang.Class [英] Java: .class file and java.lang.Class

查看:75
本文介绍了Java:.class文件和java.lang.Class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java.lang.Class与实际的.class文件相同吗?即内容是否相等?

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

我想通过套接字发送.class,并且想知道是否可以代替java.lang.Class而不是尝试查找并加载实际的.class文件?

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)

假设我有一个名为SomeObj的Java类.编译该文件后,将生成一个名为SomeObj.class的文件.

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

我们还知道,如果我将SomeObj作为类型,则可以通过执行以下操作获取其java.lang.Class类型:

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;

我们知道java.lang.Class实现了Serializable,因此可以传输它.

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

java.lang.Class基本上是实际.class文件的对象表示吗?

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

更新:

假设我已将.class文件传输到另一台主机,我是否仅使用defineClass()方法来构造该类呢?

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

链接此处

UPDATE2:

此代码确实返回空的InputStream.那怎么可能?

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());
}

推荐答案

否. java.lang.Class是一个Java类.它具有自己的.class文件:-) java.lang.Class实例用于表示对象的类,允许您执行某些操作(例如,使用反射API)在上面.

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.

串行化与.class文件完全无关-序列化的是对象状态.如果要序列化Class<MyObject>并通过电线将其发送到没有MyObject.class的JVM,它仍然不会知道MyObject是什么.

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.

为什么您需要手动首先通过网络发送.class?有远程类加载器可以解决这个问题.

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

这篇关于Java:.class文件和java.lang.Class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆