java 反射,插件机制,简易插件
1 新建一个项目 iaction,并export为iaction.jar package com.tianditu.iaction; public interface IFly { public void fly(); } 2 新建一个项目 action,引用上述jar包,并实现接口IFly package com.tianditu.action; import com.tianditu.iaction.IFly; public class Firefly implements IFly { @Override public void fly() { System.out.println("萤火虫在飞翔"); } } 3 新建一个项目 exam,并引用iaction.jar包 package com.tianditu.exam; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import com.tianditu.iaction.IFly; public class Program { public static void main(String[] args) { try { URL url=new URL("file:c:/action.jar");//将action.jar放到某个位置 URLClassLoader myClassLoader=new URLClassLoader(new URL[]{url},Thread.currentThread().getContextClassLoader()); Class<?> myClass=myClassLoader.loadClass("com.tianditu.action.Firefly");//反射实例化 IFly firefly=(IFly)myClass.newInstance(); firefly.fly(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }