什么是Class对象(java.lang.Class)? [英] what is the Class object (java.lang.Class)?

查看:164
本文介绍了什么是Class对象(java.lang.Class)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说:


Java虚拟机作为类加载,并通过调用类加载器中的 defineClass 方法。


这些对象是什么?是否与通过调用 new



实例化的对象相同?例如 object.getClass()。getName()如何将一切代码转换为超类,即使我不继承 java.lang.Class

解决方案

c> Class 。 Java中的每个对象属于某个。这就是为什么所有其他类继承的 Object 类定义 getClass()方法。



getClass()或类文字 - Foo.class 返回对象,其中包含关于类的一些元数据:




  • name

  • 方法

  • li>
  • 注释



和一些有用的方法,例如投放和各种检查( isAbstract () isPrimitive()等)。 javadoc 准确显示了您可以获取有关类的信息。 / p>

因此,例如,如果你的一个方法被赋予一个对象,并且你希望处理它,以便用 @Processable 注释,然后:

  public void process(Object obj){
if .getClass()。isAnnotationPresent(Processable.class)){
// process somehow;
}
}

在此示例中,的给定对象(无论是什么),并检查它是否有给定的注释。 Class 实例上的许多方法称为反射操作,或简称为反射。

请注意,枚举和接口也代表一个 Class 对象,并具有相应的元数据。



总结 - java中的每个对象都有,并且具有相应的 Class 对象,其包含关于它的元数据,其可在运行时访问。


The Java documentation for Class says:

Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

What are these Class objects? Are they the same as objects instantiated from a class by calling new?

Also, for example object.getClass().getName() how can everything be typecasted to superclass Class, even if I don't inherit from java.lang.Class?

解决方案

Nothing gets typecasted to Class. Every Object in Java belongs to a certain class. That's why the Object class, which is inherited by all other classes, defines the getClass() method.

getClass(), or the class-literal - Foo.class return a Class object, which contains some metadata about the class:

  • name
  • package
  • methods
  • fields
  • constructors
  • annotations

and some useful methods like casting and various checks (isAbstract(), isPrimitive(), etc). the javadoc shows exactly what information you can obtain about a class.

So, for example, if a method of yours is given an object, and you want to process it in case it is annotated with the @Processable annotation, then:

public void process(Object obj) {
    if (obj.getClass().isAnnotationPresent(Processable.class)) {
       // process somehow; 
    }
}

In this example, you obtain the metadata about the class of the given object (whatever it is), and check if it has a given annotation. Many of the methods on a Class instance are called "reflective operations", or simply "reflection. Read here about reflection, why and when it is used.

Note also that enums and interfaces also represent a Class object, and have the respective metadata.

To summarize - each object in java has (belongs to) a class, and has a respective Class object, which contains metadata about it, that is accessible at runtime.

这篇关于什么是Class对象(java.lang.Class)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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