Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

The method of obtaining class by java

Shulou Source: shulou.com Published: 2022-05-31 10:48:29 10月15日 Update

Most people do not understand the knowledge points of this article "java's method of obtaining class", so the editor summarizes the following, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "java's way to get class".

Description

1. The specific class is known, and obtained through the class attribute of the class, this method is the most secure and reliable, and the program performance is the highest.

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

3. Get the static method forName () of Class. The full class name of a class is known, and the class may throw a ClassNotFoundException under the classpath (more commonly used)

4. Through the class loader

ClassLoader cl = this.getclass () .getClassLoader (); Class clazz = cl.loadClass ("full class name")

Example

@ Testpublic void test2 () throws ClassNotFoundException {/ / method 1: call the properties of the runtime class:. Class Class clazz1 = Person.class; System.out.println (clazz1); / / class cn.bruce.java.Person / / method 2: through the object of the runtime class, call getClass () Person p1 = new Person (); 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 / / Mode 4: use the class loader: ClassLoader (understand) 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 content of this article on "how to obtain class by java". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to learn more about the relevant knowledge, please follow the industry information channel.

Tags: Method content way instance object property article knowledge article class name static run highest security value most that is commonly used performance more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Shulou Tech Info Linux Shulou Technology Docker