[Java] Class object

xiaoxiao2021-03-06  80

The Java program can correspond to a Class object at runtime, which can be obtained from the class object from the Class object, for example:

-------------------------------------------------- ---------------------

Public class myclass {

Public static void main (string [] args) {string name = "zhujun"; class c = name.getClass (); system.out.println ("getname:" c.getname ()); system.out.println ("Isinterface:" C.isinterface ()); System.out.println ("isprimities:" C.isprimitive ()); System.out.println ("Isarray:" C.isaRray ()); system .out.println ("superclass:" c.getsuperclass (). getName ());}}} output:

GetName: java.lang.stringisinterface: Falseisprimities: FalseisArray: Falsesuperclass: java.lang.object

-------------------------------------------------- ---------------------

For simple types Boolean, Byte, CHAR, SHORT, INT, Long, Float, Double, and keyword void, the corresponding Class object can be obtained by class constant class, for example:

-------------------------------------------------- ---------------------

Public class myclass {public static void main (string [] args) {system.Out.println (boolean.class.getname ()); system.class.println (boolean.class.indln; system.out.println (void.class.getname ());}}

Output results:

Boolean True Void

-------------------------------------------------- ---------------------

The Class class has a forName () static method, which can be obtained from the corresponding class name (Class Name), for example::

-------------------------------------------------- ---------------------

Class testclass {

Void Say () {

System.out.println ("this is instance of testclass):

}} Public class Main {public static void main (String [] args) {try {Class c = Class.forName ( "TestClass"); TestClass testClass = c.newInstance (); testClass.say ();} catch (ClassNotFoundException e) {E.PrintStackTrace ();}}} output:

This is instance of testclass, IS ISTANCE OF TESTCLASS

-------------------------------------------------- ---------------------

转载请注明原文地址:https://www.9cbs.com/read-54122.html

New Post(0)