Home  >  Article  >  Java  >  What are the ways to obtain classes in java

What are the ways to obtain classes in java

WBOY
WBOYforward
2023-05-12 14:34:062349browse

Acquisition method

1. If you know a specific class, obtain it through the class attribute of the class. This method is the safest and most reliable, and has the highest program performance.

2. If you know an instance of a certain class, call the getclass() method of the instance to obtain the Class object.

3. The full class name is known, and the class is on the class path and can be obtained through the static method forName() of the Class class. ClassNotFoundException may be thrown, which is more commonly used.

4. Through the class loader.

Example

@Test
public void test2() throws ClassNotFoundException {
    //方式一:调用运行时类的属性:.class
    Class<Person> clazz1 = Person.class;
    System.out.println(clazz1);//class cn.bruce.java.Person
 
    //方式二:通过运行时类的对象,调用getClass()
    Person p1 = new Person();
    Class<? extends Person> clazz2 = p1.getClass();
    System.out.println(clazz2);//class cn.bruce.java.Person
 
    //方式三:调用Class的静态方法:forName(String classPath)
    Class<?> clazz3 = Class.forName("cn.bruce.java.Person");
    System.out.println(clazz3);//class cn.bruce.java.Person
 
    System.out.println(clazz1 == clazz2);//true
    System.out.println(clazz1 == clazz3);//true
    //方式四:使用类的加载器:ClassLoader  (了解)
    ClassLoader classLoader = ReflectionTest.class.getClassLoader();
    Class<?> clazz4 = classLoader.loadClass("cn.bruce.java.Person");
    System.out.println(clazz4);//class cn.bruce.java.Person
    System.out.println(clazz1 == clazz4);//true
}

The above is the detailed content of What are the ways to obtain classes in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete