Home > Java > javaTutorial > body text

How to get class in java

王林
Release: 2023-04-18 15:55:08
forward
1697 people have browsed it

Explanation

1. If the specific class is known, it can be obtained through the class attribute of the class. This method is the safest and most reliable and has the highest program performance.

2. Known For an instance of a class, call the getclass() method of the instance to obtain the Class object

3. Obtain the static method forName() of the Class class. If the full class name of a class is known and the class is on the class path, ClassNotFoundException may be thrown (more commonly used)

4. Through the class loader

ClassLoader cl = this.getclass().getClassLoader(); Class clazz = cl.loadClass("类的全类名");
Copy after login

Instance

@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
}
Copy after login

The above is the detailed content of How to get class in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template