首页 课程 师资 教程 报名

Java反射获取类对象的方法

  • 2022-11-09 09:16:51
  • 1905次 星辉

Java反射获取类对象的方法有哪些?星辉小编来告诉大家。

1.若已知具体的类,通过类的class属性获取(该方法最为安全可靠,程序性能最高)。

Class classa = Cats.class;

通过类名.class获取

2.已知某个类的实例,调用该实例的getClass()方法获取Class对象

Cats cats = new Cats();
Class classb = cats.getClass();

通过对象名.getClass()获取

3.已知一个类的全类名,且知道该类所在的类路径,可以通过Class类的静态方法forName()获取,使用这种方法需要拋出 ClassNotFoundException异常

Class classc = Class.forName("Reflection.Cats");

通过Class.forName(需要反射的类路径)获取

4. 内置的基本数据类型可以直接用类名.Type

Class type = Integer.TYPE;

通过基本数据类型的类名.TYPE获取

5.利用ClassLoader获取

ClassLoader classLoader = new Tests().getClass().getClassLoader();
Class classd = classLoader.loadClass("Reflection.Cats");

Tests为当前类,通过这个类获取类加载器,然后通过类加载器获取类对象

整体代码如下:

package Reflection;
public class Tests {
    public static void main(String[] args) throws ClassNotFoundException {
        Cats cats = new Cats();
        System.out.println(cats.name); 
        //1.通过类名.class获取
        Class classa = Cats.class;
        System.out.println(classa);
        System.out.println(classa.hashCode()); 
        //2.通过对象获取
        Class classb = cats.getClass();
        System.out.println(classb);
        System.out.println(classb.hashCode());
        //3.通过forName获取
        Class classc = Class.forName("Reflection.Cats");
        System.out.println(classc);
        System.out.println(classc.hashCode()); 
        //4.内置基本数据类型通过TYPE属性
        Class type = Integer.TYPE;
        System.out.println(type);
        System.out.println(type.hashCode()); 
        //5.利用ClassLoader获取
        ClassLoader classLoader = new Tests().getClass().getClassLoader();
        Class classd = classLoader.loadClass("Reflection.Cats");
        System.out.println(classd);
        System.out.println(classd.hashCode());
    }
} 
class Cats{
    public String name;
    public int age;
    Cats() {
        this.name = "cat";
    }
}

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交