【问题标题】:NoClassDefError when using classes from a .jar使用 .jar 中的类时出现 NoClassDefError
【发布时间】:2018-07-08 04:42:40
【问题描述】:

我正在尝试在我的 .java 文件 Tweetauthent 中使用 .jar 文件中的类。 .jar 文件位于另一个目录中。我向 Twitter rest api 发出请求以获取承载令牌。 Tweetauthent 在我运行时编译

     -javac -cp /path/to/jar Tweetauthent.java

这是代码

import java.io.BufferedReader;
import java.lang.StringBuilder;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;

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();
}

}

我运行时遇到的错误

   java Tweetauthent

    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

据我了解,当 JVM 找不到 .java 文件用于编译的必要类文件时,会引发 NoClassDefFoundError。什么会导致这种情况?有没有办法添加jar的路径-java?哦,还有预期的消费者密钥和秘密字符串。

更新:当我将类路径添加到 java 时

    java /path/to/jar Tweethauthent

我得到错误:无法找到或加载主类 Tweetauthent

任何帮助将不胜感激谢谢!

【问题讨论】:

    标签: java linux jar javac noclassdeffounderror


    【解决方案1】:

    您遇到了运行时类路径问题。

    我看不出您是如何设置运行时类路径的。您编译的事实是必要的,但还不够。

    要么您没有正确设置运行时类路径,要么 JAR 不是您的包的一部分。

    【讨论】:

    • 好的,谢谢!我将类路径和 java 命令添加到“错误:找不到或加载主类 Tweetauthent”有什么建议吗?
    • 还是不对。要么您没有该名称的 .class 文件,其中包含 main 方法,要么该 .class 文件不在类路径中。继续前进。
    【解决方案2】:

    您需要在java 命令的-classpath-cp 选项中引用运行时依赖项:

    java -classpath /path/to/jar Tweetauthent
    

    如果您想使用参数运行,请将它们作为参数添加到 Java 文件之后:

    java -classpath /path/to/jar Tweetauthent <consumerkey> <consumersecret>
    

    【讨论】:

    • 是的,但是第一个命令是 javac(用于编译),而他调用的第二个命令 java 缺少类路径选项。
    • facepalm 我的错。不知何故,我没有看到java Tweetauthent 行。
    • 谢谢!对不起,我应该提到我尝试添加类路径,我得到“错误:无法找到或加载主类 Tweetauthent”
    • 您是否尝试使用 FQN(完全限定名称)运行它 -> java -cp ... my.pacakge.Tweetauthent ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    相关资源
    最近更新 更多