一、前言
1.通过keycloak的keycloak-proxy-server-3.4.2的jar包中org.keycloak.proxy.Main代理类,定义类启动加载器Launcher,代码示例如下
package test;@b@@b@import java.io.File;@b@import java.lang.reflect.Method;@b@import java.net.URI;@b@import java.net.URISyntaxException;@b@import java.net.URL;@b@import java.net.URLClassLoader;@b@import java.util.ArrayList;@b@import java.util.List;@b@import java.util.regex.Matcher;@b@import java.util.regex.Pattern;@b@@b@public class Launcher {@b@@b@ public static File getHome() {@b@ String launcherPath = Launcher.class.getName().replace('.', '/')@b@ + ".class";@b@ URL jarfile = Launcher.class.getClassLoader().getResource(launcherPath);@b@ if (jarfile != null) {@b@ Matcher m = Pattern.compile("jar:(file:.*)!/" + launcherPath)@b@ .matcher(jarfile.toString());@b@ if (m.matches()) {@b@ try {@b@ File jarPath = new File(new URI(m.group(1)));@b@ File libPath = jarPath.getParentFile().getParentFile();@b@ System.out.println("Home directory: " + libPath.toString());@b@ if (!libPath.exists()) {@b@ System.exit(1);@b@@b@ }@b@ return libPath;@b@ } catch (URISyntaxException e) {@b@ throw new RuntimeException(e);@b@ }@b@ }@b@ } else {@b@ System.err.println("jar file null: " + launcherPath);@b@ }@b@ return null;@b@ }@b@@b@ public static void main(String[] args) throws Exception {@b@@b@ File home = getHome();@b@ File lib = new File(home, "lib");@b@ if (!lib.exists()) {@b@ System.err.println("Could not find lib directory: "@b@ + lib.toString());@b@ System.exit(1);@b@ }@b@ List<URL> jars = new ArrayList<URL>();@b@ for (File file : lib.listFiles()) {@b@ jars.add(file.toURI().toURL());@b@ }@b@ URL[] urls = jars.toArray(new URL[jars.size()]);@b@ URLClassLoader loader = new URLClassLoader(urls,@b@ Launcher.class.getClassLoader());@b@@b@ Class mainClass = loader.loadClass("org.keycloak.proxy.Main");@b@ Method mainMethod = null;@b@ for (Method m : mainClass.getMethods())@b@ if (m.getName().equals("main")) {@b@ mainMethod = m;@b@ break;@b@ }@b@ Object obj = args;@b@ mainMethod.invoke(null, obj);@b@ }@b@}
2.运行上面代码示例,报“Exception in thread "main" java.lang.ClassNotFoundException: org.keycloak.proxy.Main”错误异常,详情如下
Exception in thread "main" java.lang.ClassNotFoundException: org.keycloak.proxy.Main@b@ at java.net.URLClassLoader$1.run(URLClassLoader.java:366)@b@ at java.net.URLClassLoader$1.run(URLClassLoader.java:355)@b@ at java.security.AccessController.doPrivileged(Native Method)@b@ at java.net.URLClassLoader.findClass(URLClassLoader.java:354)@b@ at java.lang.ClassLoader.loadClass(ClassLoader.java:425)@b@ at java.lang.ClassLoader.loadClass(ClassLoader.java:358)@b@ at test.Launcher.main(Launcher.java:56)
二、解决方法
根据错误异常“java.lang.ClassNotFoundException: org.keycloak.proxy.Main”,因为缺少对于的keycloak-proxy-server-3.4.2.Final.jar代理服务依赖包导致,下载导入到项目lib后,访问解决了。