在 Java 项目中使用 android.jar - RuntimeException Stub?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7247502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:16:09  来源:igfitidea点击:

Using android.jar in Java project - RuntimeException Stub?

javaandroid

提问by emeraldhieu

I tried to include android.jarinto Java project, remove JRE from Build Pathand run this code. It throws Runtime exception. Why?

我尝试将android.jar 包含到 Java 项目中,从 Build Path 中删除 JRE并运行此代码。它抛出运行时异常。为什么?

Exception in thread "main" java.lang.RuntimeException: Stub!
    at android.content.ContentValues.<init>(ContentValues.java:5)
    at JarTest.main(JarTest.java:5)

public class JarTest {
    public static void main(final String[] args) {
        final ContentValues values = new ContentValues();
        values.put("test", "test");
        System.out.println(values);
    }
}

Why is ContentValues used only in Android environment?

为什么 ContentValues 只在 Android 环境中使用?

回答by antlersoft

The android.jar in the SDK only contains stub implementations of the SDK classes, not the real implementations that are found on the devices (or emulator). The jar just provides the class metadata so that your apps that reference the SDK classes will build properly.

SDK 中的 android.jar 仅包含 SDK 类的存根实现,而不是在设备(或模拟器)上找到的真实实现。该 jar 仅提供类元数据,以便您引用 SDK 类的应用程序能够正确构建。

You can't create any project that references the android.jar that will run outside an Android device.

您不能创建任何引用将在 Android 设备外部运行的 android.jar 的项目。

回答by soulseekah

android.jar contains stubs only, enough to let you build your project, as @antlersoft explained.

android.jar 仅包含存根,足以让您构建项目,正如@antlersoft 所解释的那样。

The Robolectric project http://robolectric.org/allows you to run tests on your Android code without using a device. They have real builds available on Maven http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.robolectric%22

Robolectric 项目http://robolectric.org/允许您在不使用设备的情况下对 Android 代码运行测试。他们在 Maven http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22org.robolectric%22上有真正的构建可用

I have been successfully running most of the Android backend code by using the android-allartifact.

我已经通过使用android-all工件成功运行了大部分 Android 后端代码。

Might not help in your specific case, since some APIs are still out of bounds, but for most other cases of java.lang.RuntimeException: Stub!including the artifacts from Robolectric should help.

在您的特定情况下可能无济于事,因为某些 API 仍然超出范围,但对于大多数其他情况,java.lang.RuntimeException: Stub!包括来自 Robolectric 的工件应该会有所帮助。