java自定义ClassLoader加载指定的class文件实现例子
SyncExternalClassLoader loader = new SyncExternalClassLoader(); Class<?> aClass = loader.findClass("bug"); object = aClass.newInstance();
public class SyncExternalClassLoader extends ClassLoader { @Override public Class<?> findClass(String name) { String myPath = "file:///D:/infosec/netauth/accountsync/SynchAccountToCertAuth.class"; System.out.println(myPath); byte[] cLassBytes = null; Path path = null; try { path = Paths.get(new URI(myPath)); cLassBytes = Files.readAllBytes(path); } catch (IOException | URISyntaxException e) { e.printStackTrace(); } Class clazz = defineClass("infosec.netauth.accountsync.SynchAccountToCertAuth", cLassBytes, 0, cLassBytes.length); return clazz; } }
boolean interfaceFlag = guessInterface(object);
private boolean guessInterface(Object object) { if (object instanceof SynchAccountApi) { return true; } if (object instanceof SyncUsersFromAppInterface) { return true; } Class<?>[] allInterfaces = ClassUtils.getAllInterfaces(object); return Arrays.stream(allInterfaces).anyMatch(aClass -> aClass.getName().contains("SynchAccountApi")); }
private List<PropertiesBean> getPropertiesBean(){ SyncExternalClassLoader loader = new SyncExternalClassLoader(); Class<?> aClass = loader.findClass("bug"); Object object; try { object = aClass.newInstance(); Method method = aClass.getMethod("getProperties"); List<PropertiesBean> list = (List<PropertiesBean>) method.invoke(object); return list; } catch (Exception e) { e.printStackTrace(); } return null; }