Home Java javaTutorial What does class mean in java?

What does class mean in java?

May 17, 2019 pm 03:52 PM
class java

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

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

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{

    }}
Copy after login

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();
    }
Copy after login

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;
Copy after login

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();
    }
Copy after login

Output result

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

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));
Copy after login

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 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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

See all articles