使用外部Jar类时出现NoClassDefFoundError及主类加载问题求助
解决Java运行时
NoClassDefFoundError问题及Twitter Bearer Token获取调试 我完全明白你碰到的困境——编译顺利通过,但运行时JVM找不到依赖的JSON类,这是Java开发里很常见的classpath配置问题,咱们一步步来解决:
核心问题分析
你编译时用了javac -cp /path/to/jar Tweetauthent.java,这个-cp参数告诉编译器去哪里找依赖类,所以编译成功了;但运行java Tweetauthent时,JVM默认只会在当前工作目录查找类文件,没有包含你依赖的那个Jar包,自然找不到org/json/simple/JSONValue类,就抛出了NoClassDefFoundError。你之前尝试的java /path/to/jar Tweetauthent是错误的命令格式,Jar路径不能直接放在主类前面,必须通过-cp参数指定。
正确的运行命令
Linux/macOS系统
java -cp .:/path/to/your/json-simple.jar Tweetauthent
Windows系统
java -cp .;C:\path\to\your\json-simple.jar Tweetauthent
.代表当前目录,确保JVM能找到你编译好的Tweetauthent.class文件:(Linux/macOS)或;(Windows)是多个classpath路径的分隔符/path/to/your/json-simple.jar替换成你实际的Jar包完整路径
如果有多个依赖Jar,还可以用通配符简化:
# Linux/macOS java -cp .:/path/to/jars/* Tweetauthent
代码里的小细节修正
另外看你的代码,发现一个可能导致认证失败的小问题:在requestBearerToken方法里,你写的是:
String encodedCredentials = encodeKeys("<consumerkey>","<consumersecret>");
这里应该替换成你类里定义的静态变量,不然会用字面量字符串去编码,导致Twitter认证失败:
String encodedCredentials = encodeKeys(consumerkey, consumersecret);
你提供的错误信息
java.lang.NoClassDefFoundError: org/json/simple/JSONValue at Tweetauthent.requestBearerToken(Tweetauthent.java:61) at Tweetauthent.main(Tweetauthent.java:27) Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONValue at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 2 more
你提供的修正后代码
import java.io.BufferedReader; import java.lang.StringBuilder; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URLEncoder; import java.net.URL; import java.net.HttpsURLConnection; import java.util.Base64; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class Tweetauthent{ static String consumerkey = "astring"; static String consumersecret = "astring"; static String endurl = "https://api.twitter.com/oauth2/token"; public static void main(String []args){ Tweetauthent t = new Tweetauthent(); try{ System.out.println(t.requestBearerToken(endurl)); }catch(IOException e){ System.out.println(e); } } public static String encodeKeys(String consumerKey,String consumerSecret){ try{ String encodedConsumerKey = URLEncoder.encode(consumerKey,"UTF-8"); String encodedConsumerSecret = URLEncoder.encode(consumerSecret,"UTF-8"); String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret; byte[] encodedBytes = Base64.getEncoder().encode(fullKey.getBytes()); return new String(encodedBytes); }catch(UnsupportedEncodingException e){ return new String(); } } public static String requestBearerToken(String endPointURL) throws IOException { HttpsURLConnection connection = null; String encodedCredentials = encodeKeys(consumerkey, consumersecret); // 修正参数引用 try{ URL url = new URL(endPointURL); connection = (HttpsURLConnection)url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestProperty("Host","api.twitter.com"); connection.setRequestProperty("User-Agent","TweetPersonalityAnalyzer"); connection.setRequestProperty("Authorization","Basic " + encodedCredentials); connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); connection.setRequestProperty("Content-Length","29"); writeRequest(connection, "grant_type=client_credentials"); JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection)); if(obj != null){ String tokenType = (String)obj.get("token_type"); String token = (String)obj.get("access_token"); return ((tokenType.equals("bearer")) && (token != null)) ? token : ""; } return new String(); }catch(MalformedURLException e){ throw new IOException("Invalid endpoint URL specified.", e); } finally{ if( connection != null){ connection.disconnect(); } } } public static boolean writeRequest(HttpsURLConnection connection, String textBody){ try{ BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); wr.write(textBody); wr.flush(); wr.close(); return true; } catch(IOException e){ return false; } } public static String readResponse(HttpsURLConnection connection){ try { StringBuilder str = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = ""; while((line = br.readLine()) != null){ str.append(line + System.getProperty("line.separator")); } return str.toString(); }catch(IOException e){ return new String(); } } }
内容的提问来源于stack exchange,提问作者brad
相关产品推荐
相关产品推荐

