Class of JAVA

Note: Based on jdk11

Class

An instance of Class class represents classes and interfaces in a runtime java application. Enumeration type is a kind, annotation Class is an interface. Arrays share the same kind. base
 This type (boolean, byte, char, short, int, long, float, and double) and the keyword void are also represented as class objects.
Class has no public constructor and can only be created by the JVM. When the classloader calls the defineClass method and passes the class file bytes to the JVM, the JVM will automatically build
 Class object.

The following interfaces are implemented

1. java.io.Serializable
2. GenericDeclaration
  GenericDeclaration all entities that declare generic variables need to implement this interface (Note: I will explain in "JAVA generics" later)
  The only way:
  Public TypeVariable <? > [] gettypeparameters(); / / get the generic variable declared on the current entity.
3. Type 
  Type is a common high-level interface of all types in java language, including primitive type, parameterized type, array type, generic variable and basic type.
  Default method:
  default String getTypeName() {
      return toString();
  }

4. AnnotatedElement
  The java.lang.reflect.AnnotatedElement interface defines the annotation element that gets the program running in the current JVM. This interface allows annotations to be retrieved by reflection. The annotations obtained through the current interface method are immutable and serialized.

Several key methods

  1. forName()
      public static Class<?> forName(String className)
                  throws ClassNotFoundException {
          Class<?> caller = Reflection.getCallerClass();
          return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
      }

      @CallerSensitive
      public static Class<?> forName(String name, boolean initialize,
                                     ClassLoader loader)
          throws ClassNotFoundException
      {
          Class<?> caller = null;
          SecurityManager sm = System.getSecurityManager();
          if (sm != null) {
              // Reflective call to get caller class is only needed if a security manager
              // is present.  Avoid the overhead of making this call otherwise.
              caller = Reflection.getCallerClass();
              if (loader == null) {
                  ClassLoader ccl = ClassLoader.getClassLoader(caller);
                  if (ccl != null) {
                      sm.checkPermission(
                          SecurityConstants.GET_CLASSLOADER_PERMISSION);
                  }
              }
          }
          return forName0(name, initialize, loader, caller);
      }

      /** Called after security check for system loader access checks have been made. */
      private static native Class<?> forName0(String name, boolean initialize,
                                              ClassLoader loader,
                                              Class<?> caller)
          throws ClassNotFoundException;

Several ways to obtain Class object reference

1. Integer.class
2. new Integer(1).getClass()
3. Class.forName("java.lang.Integer")

Code example

    package chapter03;

  import java.lang.annotation.ElementType;
  import java.lang.reflect.InvocationTargetException;

  public class TestClass {

      public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {

          System.out.println("--- 3 mode get obj's Class ---");
          System.out.println(Integer.class);
          System.out.println(Integer.valueOf(1).getClass());
          System.out.println(Class.forName("java.lang.Integer"));
          System.out.println(int.class);
          System.out.println("int is privitive type or not ? " + int.class.isPrimitive());

          // array
          System.out.println("--- array' Class ---");
          System.out.println(new Integer[]{1, 3, 5}.getClass());
          System.out.println(new Object[]{1, 3, 5}.getClass());
          System.out.println(new Integer[][]{{1, 2, 3}, {2, 3, 4}, {3, 4, 5}}.getClass());

          // void package
          System.out.println("--- void & package' Class ---");
          System.out.println(Void.class);
          System.out.println(void.class);
          System.out.println(Package.class);

          // enum
          System.out.println("--- enum' Class ---");
          System.out.println(ElementType.class);
          System.out.println("ElementType is enum or not ? " + ElementType.class.isEnum());

          // annotation
          System.out.println("--- annotation' Class ---");
          System.out.println(Deprecated.class);
          System.out.println("Deprecated is interface or not ? " + Deprecated.class.isInterface());
          System.out.println("Deprecated is annotation or not ? " + Deprecated.class.isAnnotation());

          // class' Class
          System.out.println("--- class' Class ---");
          System.out.println(Class.forName("java.lang.Integer").getClass());

          // module
          System.out.println(Class.forName("chapter03.Test").getModule());

          //new instance
          System.out.println(Class.forName("chapter03.Test").getDeclaredConstructor());
          Class.forName("chapter03.Test").getDeclaredConstructor().newInstance();
          Class.forName("chapter03.Test").newInstance();

      }
  }

  class Test {
      private Test() {

      }
  }
  
  //Print results:
  
  --- 3 mode get obj's Class ---
  class java.lang.Integer
  class java.lang.Integer
  class java.lang.Integer
  int
  int is privitive type or not ? true
  --- array' Class ---
  class [Ljava.lang.Integer;
  class [Ljava.lang.Object;
  class [[Ljava.lang.Integer;
  --- void & package' Class ---
  class java.lang.Void
  void
  class java.lang.Package
  --- enum' Class ---
  class java.lang.annotation.ElementType
  ElementType is enum or not ? true
  --- annotation' Class ---
  interface java.lang.Deprecated
  Deprecated is interface or not ? true
  Deprecated is annotation or not ? true
  --- class' Class ---
  class java.lang.Class
  unnamed module @67b64c45
  private chapter03.Test()
  Exception in thread "main" java.lang.IllegalAccessException: class chapter03.TestClass cannot access a member of class chapter03.Test with modifiers "private"
      at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:361)
      at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:591)
      at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
      at chapter03.TestClass.main(TestClass.java:50)

Tags: Java jvm JDK

Posted on Sat, 11 Jan 2020 08:11:38 -0800 by kattar