1、使用Class类的静态方法Class.forName("xxxx");
新建一个要想要获取的类
package org.burning.sport.javase.classloader; public class ClassLoaderModel { }
package org.burning.sport.javase.classloader; /** * 类的载入方式 */ public class ClassLoaderMain { public static void main(String[] args) { ClassLoaderMain clm = new ClassLoaderMain(); //1.使用Class静态方法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、使用ClassLoader
package org.burning.sport.javase.classloader; /** * 类的载入方式 */ public class ClassLoaderMain { public static void main(String[] args) { ClassLoaderMain clm = new ClassLoaderMain(); //2.使用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、使用 类.class
package org.burning.sport.javase.classloader; /** * 类的载入方式 */ public class ClassLoaderMain { public static void main(String[] args) { ClassLoaderMain clm = new ClassLoaderMain(); //3. 使用类.class方式 clm.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、使用对象的getClass方法
package org.burning.sport.javase.classloader; /** * Created by lisen on 2017/7/27. * 类的载入方式 */ public class ClassLoaderMain { public static void main(String[] args) { ClassLoaderMain clm = new ClassLoaderMain(); //4. 使用对象的getClass方法 clm.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
时间: 2024-10-14 01:54:57