1, the use of class static method Class.forName ("xxxx");
Create a new class that you want to get
Package Org.burning.sport.javase.classloader; Public class Classloadermodel {}
PackageOrg.burning.sport.javase.classloader;/*** Class loading mode*/ Public classClassloadermain { Public Static voidMain (string[] args) {classloadermain CLM=NewClassloadermain (); //1. Using the class static method Class.forNameclm.loadclassmethod1 (); } Public voidloadClassMethod1 () {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. Using ClassLoader
PackageOrg.burning.sport.javase.classloader;/*** Class loading mode*/ Public classClassloadermain { Public Static voidMain (string[] args) {classloadermain CLM=NewClassloadermain (); //2. Using ClassLoaderclm.loadclassmethod2 (); } Public voidloadClassMethod2 () {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 classes. Class
PackageOrg.burning.sport.javase.classloader;/*** Class loading mode*/ Public classClassloadermain { Public Static voidMain (string[] args) {classloadermain CLM=NewClassloadermain (); //3. Use classes. Class Modeclm.loadclassmethod3 (); } Public voidloadClassMethod3 () {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. GetClass method of using object
PackageOrg.burning.sport.javase.classloader;/*** Created by Lisen on 2017/7/27. * Class Loading mode*/ Public classClassloadermain { Public Static voidMain (string[] args) {classloadermain CLM=NewClassloadermain (); //4. GetClass method for using objectsclm.loadclassmethod4 (); } Public voidloadClassMethod4 () {Classloadermodel CLM=NewClassloadermodel (); 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
javase-Reflection-Four ways to get classes or objects