JavaSE-reflection-four methods for obtaining classes or objects, and javase-four methods
1. Use Class static method Class. forName ("xxxx ");
Create a class to be obtained
package org.burning.sport.javase.classloader;public class ClassLoaderModel {}
Package org. burning. sport. javase. classloader;/*** class Loading Method */public class ClassLoaderMain {public static void main (String [] args) {ClassLoaderMain clm = new ClassLoaderMain (); // 1. use the Class static method Class. forName clm. loadClassMethod1 ();} public void loadClassMethod1 () {try {Class <?> Clazz = Class. forName ("org. burning. sport. javase. classloader. classLoaderModel "); ClassLoaderModel clm = (ClassLoaderModel) clazz. newInstance (); System. out. println (clm);} catch (Exception e) {e. printStackTrace ();}}}
2. Use ClassLoader
Package org. burning. sport. javase. classloader;/*** class Loading Method */public class ClassLoaderMain {public static void main (String [] args) {ClassLoaderMain clm = new ClassLoaderMain (); // 2. use ClassLoader clm. loadClassMethod2 ();} public void loadClassMethod2 () {ClassLoader cl = this. getClass (). getClassLoader (); try {Class <?> Clazz = cl. loadClass ("org. burning. sport. javase. classloader. classLoaderModel "); ClassLoaderModel clm = (ClassLoaderModel) clazz. newInstance (); System. out. println (clm);} catch (Exception e) {e. printStackTrace ();}}}
3. Use class. class
Package org. burning. sport. javase. classloader;/*** class Loading Method */public class ClassLoaderMain {public static void main (String [] args) {ClassLoaderMain clm = new ClassLoaderMain (); // 3. usage class. clm in class mode. loadClassMethod3 ();} public void loadClassMethod3 () {Class <?> Clazz = ClassLoaderModel. class; try {ClassLoaderModel str = (ClassLoaderModel) clazz. newInstance (); System. out. println (str);} catch (InstantiationException e) {e. printStackTrace ();} catch (IllegalAccessException e) {e. printStackTrace ();}}}
4. Use the getClass method of the object
Package org. burning. sport. javase. classloader;/*** Created by lisen on login /7/27. * class Loading Method */public class ClassLoaderMain {public static void main (String [] args) {ClassLoaderMain clm = new ClassLoaderMain (); // 4. use the getClass method clm of the object. loadClassMethod4 ();} public void loadClassMethod4 () {ClassLoaderModel clm = new ClassLoaderModel (); Class <?> Clazz = clm. getClass (); try {ClassLoaderModel ss = (ClassLoaderModel) clazz. newInstance (); System. out. println (ss);} catch (Exception e) {e. printStackTrace ();}}}
Https://gitee.com/play-happy/base-project