1. 实现一个ClassLoad继承类
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; /** * Created by CHENWENJUN431 on 2017-03-24. */ public class ExtendelClassLoad extends ClassLoader { private static final Logger logger = LoggerFactory.getLogger(ExtendelClassLoad.class) ; private String rootDirPath ; public ExtendelClassLoad (String rootDirPath) { this.rootDirPath = rootDirPath; } private byte[] getClassData(String className) { String path = rootDirPath + File.separatorChar + className.replace(".",File.separator) + ".class"; try{ InputStream ins = new FileInputStream(path) ; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int buffersize = 4096; byte[] buffer = new byte[buffersize]; int readtemp = 0; if((readtemp = ins.read(buffer)) != -1 ) { baos.write(buffer,0,readtemp); } return baos.toByteArray(); }catch (FileNotFoundException e) { }catch (IOException e) { } return null; } protected Class<?> findClassByName (String className) throws ClassNotFoundException { byte[] classData = getClassData(className); if(classData == null) { throw new ClassNotFoundException(); } return defineClass(className,classData,0,classData.length); } }
2. 调用
ExtendelClassLoad ecl = new ExtendelClassLoad("D:\\hiapfe\\hiap-fe\\work"); Class c = ecl.findClassByName("packagename.classname"); c.getDeclaredMethod("printSomth",String.class).invoke(c.newInstance(),"what");
注意的地方,如果java中包含包名字的话,需要在编译class路径中加上包体结构。心疼自己。。。