search
HomeJavajavaTutorialWhat does class mean in java?

What does class mean in java?

May 17, 2019 pm 03:52 PM
classjava

class means "class". It is a class in java. It defines the implementation of a specific class. It exists in the java.lang package. Its constructor is private and is loaded by the JVM (class loader). device) to create a Class object, which can be obtained through the getClass() method.

What does class mean in java?

class is a class that exists in the java.lang package. Its constructor is private and the Class object is created by the JVM (class loader). We can get the Class object through the getClass() method.

    /*
     * 私有构造函数,使得只有jvm可以创建该类的对象,这个私有构造函数还可以防止通过默认构造函数创建类对象
     */
    private Class(ClassLoader loader) {
        // 初始化final变量ClassLoader
        classLoader = loader;
    }

Class class is an implementation that defines a specific class in the Java language. The definition of a class includes member variables, member methods, interfaces implemented by the class, and the parent class of the class. Objects of the Class class are used to represent classes and interfaces in the currently running Java application. For example: each array belongs to a Class object, and all arrays with the same element type and dimension share a Class object. Basic Java types (boolean, byte, char, short, int, long, float and double) and void types can also be represented as Class objects.

Class object, through which we can get the attributes, methods, etc. of the created class.

What does class mean in java?

The role of the Class class

(1) Get the type of attributes in the class

(2) Get The name of the attribute in the class

(3) Get the method of the class

(4) Get the base class of the class, etc.

(5) Based on the above, you can use it to complete reflection

Main methods of Class

1.forName method

Enter the full path name of the class that needs to be loaded and get the Class object of the class

2.newInstance method

  public T newInstance()
        throws InstantiationException, IllegalAccessException
    {
        if (System.getSecurityManager() != null) {
            checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
        }
        // NOTE: 下面的编码可能不是严格符合当前的java内存模型
        // 寻找构造器
        if (cachedConstructor == null) {
            if (this == Class.class) {
                throw new IllegalAccessException(
                    "Can not call newInstance() on the Class for java.lang.Class"
                );
            }
            try {
                Class<?>[] empty = {};
               //获取无参构造器,如果没有就抛出异常,说明这个方法只适用于有无参构造函数的类
                final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
                // 设置构造器允许访问
                java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction<Void>() {
                        public Void run() {
                                c.setAccessible(true);
                                return null;
                            }
                        });
                cachedConstructor = c;
            } catch (NoSuchMethodException e) {
                throw (InstantiationException)
                    new InstantiationException(getName()).initCause(e);
            }
        }
        Constructor<T> tmpConstructor = cachedConstructor;
        // 安全检查
        int modifiers = tmpConstructor.getModifiers();
        if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
            Class<?> caller = Reflection.getCallerClass();
            if (newInstanceCallerCache != caller) {
                Reflection.ensureMemberAccess(caller, this, null, modifiers);
                newInstanceCallerCache = caller;
            }
        }
        // 执行无参构造函数创建实例对象
        try {
            return tmpConstructor.newInstance((Object[])null);
        } catch (InvocationTargetException e) {
            Unsafe.getUnsafe().throwException(e.getTargetException());
            // Not reached
            return null;
        }
    }

3.isInstance (native method)

Implementation class used to determine whether the input parameter is the current Class object (subclass)

public class TestInfo {

    static {
        System.out.println("我是谁");
    }

    public TestInfo(){
        System.out.println("我是构造函数");
    }
    public String test="测试属性";
    public static void main(String[] args) {
        TestClass info=new TestClass();
        //返回结果是true因为info是子类的对象System.out.println(TestInfo.class.isInstance(info));
    }
    public static class TestClass extends TestInfo{

    }}

4.getName, getTypeName, getCanonicalName, getSimpleName

    public static void main(String[] args) {
        System.out.println(TestClass.class.getTypeName());
        System.out.println(TestClass.class.getCanonicalName());
        System.out.println(TestClass.class.getSimpleName());
        System.out.println(TestClass.class.getName());
        System.out.println("-------------------------------------------------------");
        System.out.println(TestClass[].class.getTypeName());
        System.out.println(TestClass[].class.getCanonicalName());
        System.out.println(TestClass[].class.getSimpleName());
        System.out.println(TestClass[].class.getName());
    }

    public static abstract class TestClass<T extends TestInfo, String> extends TestInfo implements Aware, Comparable<Integer> {
        public abstract void test();
    }

Output results

com.hikvision.test.abc.TestInfo$TestClass
com.hikvision.test.abc.TestInfo.TestClass
TestClass
com.hikvision.test.abc.TestInfo$TestClass
-------------------------------------------------------
com.hikvision.test.abc.TestInfo$TestClass[]
com.hikvision.test.abc.TestInfo.TestClass[]
TestClass[]
[Lcom.hikvision.test.abc.TestInfo$TestClass;

5.getClassLoader

Get the class loader of the current class

6.getTypeParameters

Get the generic parameter array in the generic class.

7.getSuperclass and getGenericSuperclass

both obtain parent class information, but the latter will bring generic parameters

8.getInterfaces and getGenericInterfaces

Get the interface array implemented by the current Class object, but the latter will bring the generic parameters of the interface, such as

  public static void main(String[] args) {
        System.out.println(TestClass.class.getInterfaces()[1]);
    }

    public static abstract class TestClass<T extends TestInfo,String> extends TestInfo implements Aware,BeanFactory {
        public abstract void test();
    }

Output result

interface org.springframework.beans.factory.BeanFactory
java.lang.Comparable<java.lang.Integer>

9.isAssignableFrom(native method)

This method is more anti-human. The input parameters in parentheses represent the parent class of the current Class object or the same object.

//这样返回的是false
System.out.println(TestClass.class.isAssignableFrom(TestInfo.class));

10.isInterface(native method)

Determine whether it is an interface

11.isArray(native method)

Whether it is an array

12.isPrimitive (native method)

Used to determine whether this Class object is a basic type, such as int, byte, char, etc.

13.isAnnotation

Judge this Whether the Class object is annotated

14.getComponentType

If the current Class object is an array, get the element type in the array

15.getModifiers

Get the attributes Or the enumeration value corresponding to the modifier in front of the method

16.getDeclaringClass

Get the belonging class of the method or attribute, or get the class from which the current Class object inherits

17 .getSimpleName

The class name of the Class object

18.getClasses, getDeclaredClasses

(1) Get the public-modified internal class in the Class object

(2 ) Get the inner class in the Class object, inherited members are not included

19.getFields, getField, getDeclaredFields

(1) Get the public modified attribute field

(2) Find the corresponding attribute domain according to the entered attribute name

(3) Get the attribute domain in the Class object

20.getMethods, getMethod, getDeclaredMethods

( 1) Get the public modified method

(2) Find the corresponding method

based on the input method name and input parameter type (3) Get the method

in the Class object 21.getConstructors, getConstructor, getDeclaredConstructors

(1) Get the public modified constructor

(2) Find the corresponding constructor based on the input method name and input parameter type

(3) Get the constructor in the Class object

The above is the detailed content of What does class mean in java?. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function