Java Eclipse - JAR 创建失败“找不到或无法访问类路径上的类文件...”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18300815/
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-08-12 00:15:49  来源:igfitidea点击:

Eclipse - JAR creation failed "Class files on classpath not found or not accessible for..."

javaeclipsemacosjar

提问by Andy

I have a project in Eclipse that has a red cross on it and will not export to a runnable JAR. I can't remember if I have looked at it since I reinstalled Windows on my laptop, but I know that I haven't changed any code. There are no errors in any of the classes, however the error I get points to the following class that deals with the menu items on Mac OSx:

我在 Eclipse 中有一个项目,上面有一个红叉,不会导出到可运行的 JAR。我不记得自从我在笔记本电脑上重新安装 Windows 后是否看过它,但我知道我没有更改任何代码。任何类都没有错误,但是我得到的错误指向以下处理 Mac OSx 菜单项的类:

import java.lang.reflect.*;

public class osxhandler implements InvocationHandler {

    protected Object targetObject;
    protected Method targetMethod;
    protected String proxySignature;

    static Object macOSXApplication;

    // Pass this method an Object and Method equipped to perform application shutdown logic
    // The method passed should return a boolean stating whether or not the quit should occur
    public static void setQuitHandler(Object target, Method quitHandler) {
        setHandler(new HOsx("handleQuit", target, quitHandler));
    }


    public static void setAboutHandler(Object target, Method aboutHandler) {
        boolean enableAboutMenu = (target != null && aboutHandler != null);
        if (enableAboutMenu) {
            setHandler(new HOsx("handleAbout", target, aboutHandler));
        }
        // If we're setting a handler, enable the About menu item by calling
        // com.apple.eawt.Application reflectively
        try {
            Method enableAboutMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledAboutMenu", new Class[] { boolean.class });
            enableAboutMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enableAboutMenu) });
        } catch (Exception ex) {
            System.err.println("MacOSHandler could not access the About Menu");
            ex.printStackTrace();
        }
    }

       public static void setPreferencesHandler(Object target, Method prefsHandler) {
            boolean enablePrefsMenu = (target != null && prefsHandler != null);
            if (enablePrefsMenu) {
                setHandler(new HOsx("handlePreferences", target, prefsHandler));
            }
            // If we're setting a handler, enable the Preferences menu item by calling
            // com.apple.eawt.Application reflectively
            try {
                Method enablePrefsMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledPreferencesMenu", new Class[] { boolean.class });
                enablePrefsMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enablePrefsMenu) });
            } catch (Exception ex) {
                System.err.println("MacOSHandler could not access the About Menu");
                ex.printStackTrace();
            }
        }

        // Pass this method an Object and a Method equipped to handle document events from the Finder
        // Documents are registered with the Finder via the CFBundleDocumentTypes dictionary in the 
        // application bundle's Info.plist
        public static void setFileHandler(Object target, Method fileHandler) {
            setHandler(new HOsx("handleOpenFile", target, fileHandler) {
                // Override MacOSHandler.callTarget to send information on the
                // file to be opened
                public boolean callTarget(Object appleEvent) {
                    if (appleEvent != null) {
                        try {
                            Method getFilenameMethod = appleEvent.getClass().getDeclaredMethod("getFilename", (Class[])null);
                            String filename = (String) getFilenameMethod.invoke(appleEvent, (Object[])null);
                            this.targetMethod.invoke(this.targetObject, new Object[] { filename });
                        } catch (Exception ex) {

                        }
                    }
                    return true;
                }
            });
        }

        // setHandler creates a Proxy object from the passed MacOSHandler and adds it as an ApplicationListener
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public static void setHandler(HOsx adapter) {
            try {
                Class applicationClass = Class.forName("com.apple.eawt.Application");
                if (macOSXApplication == null) {
                    macOSXApplication = applicationClass.getConstructor((Class[])null).newInstance((Object[])null);
                }
                Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener");
                Method addListenerMethod = applicationClass.getDeclaredMethod("addApplicationListener", new Class[] { applicationListenerClass });
                // Create a proxy object around this handler that can be reflectively added as an Apple ApplicationListener
                Object MacOSHandlerProxy = Proxy.newProxyInstance(HOsx.class.getClassLoader(), new Class[] { applicationListenerClass }, adapter);
                addListenerMethod.invoke(macOSXApplication, new Object[] { MacOSHandlerProxy });
            } catch (ClassNotFoundException cnfe) {
                System.err.println("This version of Mac OS X does not support the Apple EAWT.  ApplicationEvent handling has been disabled (" + cnfe + ")");
            } catch (Exception ex) {  // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking eawt.Application methods
                System.err.println("Mac OS X Adapter could not talk to EAWT:");
                ex.printStackTrace();
            }
        }

        // Each MacOSHandler has the name of the EAWT method it intends to listen for (handleAbout, for example),
        // the Object that will ultimately perform the task, and the Method to be called on that Object
        protected HOsx(String proxySignature, Object target, Method handler) {
            this.proxySignature = proxySignature;
            this.targetObject = target;
            this.targetMethod = handler;
        }

        // Override this method to perform any operations on the event 
        // that comes with the various callbacks
        // See setFileHandler above for an example
        public boolean callTarget(Object appleEvent) throws InvocationTargetException, IllegalAccessException {
            Object result = targetMethod.invoke(targetObject, (Object[])null);
            if (result == null) {
                return true;
            }
            return Boolean.valueOf(result.toString()).booleanValue();
        }

        // InvocationHandler implementation
        // This is the entry point for our proxy object; it is called every time an ApplicationListener method is invoked
        public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
            if (isCorrectMethod(method, args)) {
                boolean handled = callTarget(args[0]);
                setApplicationEventHandled(args[0], handled);
            }
            // All of the ApplicationListener methods are void; return null regardless of what happens
            return null;
        }

        // Compare the method that was called to the intended method when the MacOSHandler instance was created
        // (e.g. handleAbout, handleQuit, handleOpenFile, etc.)
        protected boolean isCorrectMethod(Method method, Object[] args) {
            return (targetMethod != null && proxySignature.equals(method.getName()) && args.length == 1);
        }

        // It is important to mark the ApplicationEvent as handled and cancel the default behavior
        // This method checks for a boolean result from the proxy method and sets the event accordingly
        protected void setApplicationEventHandled(Object event, boolean handled) {
            if (event != null) {
                try {
                    Method setHandledMethod = event.getClass().getDeclaredMethod("setHandled", new Class[] { boolean.class });
                    // If the target method returns a boolean, use that as a hint
                    setHandledMethod.invoke(event, new Object[] { Boolean.valueOf(handled) });
                } catch (Exception ex) {
                    System.err.println("MacOSHandler was unable to handle an ApplicationEvent: " + event);
                    ex.printStackTrace();
                }
            }
        }    
}

Any ideas as to why I can't export/compile? I've never had this issue before.

关于为什么我不能导出/编译的任何想法?我以前从未遇到过这个问题。

采纳答案by adarshr

Just do a clean and/or rebuild on the project.

只需对项目进行清理和/或重建。

You can find it under the Projectmenu of Eclipse.

您可以在ProjectEclipse的菜单下找到它。

回答by Dennis Kriechel

It's quite hateful that Eclipse always generates hidden files .project and .classpath in project folder. Sometimes you're not aware if something goes wrong in these files.

After upgrading your Eclipse and if you found the following compile error, I'd suggest you to check .classpath in your project folder.

The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project

Most likely you would see a line like this.

Eclipse 总是在项目文件夹中生成隐藏文件 .project 和 .classpath ,这是非常可恶的。有时您不知道这些文件中是否有问题。

升级 Eclipse 后,如果发现以下编译错误,建议您检查项目文件夹中的 .classpath。

该项目未构建,因为其构建路径不完整。找不到 java.lang.Object 的类文件。修复构建路径然后尝试构建这个项目

您很可能会看到这样的一行。

<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/    org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/j2re1.4.2_03"/>

The stupid Eclipse appended this for no reason. Just simply remove it to make it work again. ;)

/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/j2re1.4.2_xx

愚蠢的 Eclipse 无缘无故地附加了这个。只需简单地将其删除即可使其再次工作。;)

/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/j2re1.4.2_xx

Source: http://hochit.com/2006/07/06/eclipse-upgrading-problem-javalangobject-not-found/

来源:http: //hochit.com/2006/07/06/eclipse-upgrading-problem-javalangobject-not-found/

In addition, you can check your project settingsin eclipse. Right click on your project and choose properties. Go to Java Build Path and there should be more specific information of the problem. Most likely you set the JDKto an Version which doesn't exist on the new System.

此外,您可以project settings在日食中检查您的。右键单击您的项目并选择属性。转到Java Build Path,应该有更具体的问题信息。很可能您将 设置JDK为新系统上不存在的版本。

If this doesn't help too, select your project and then use the menu entry Source->Clean Up.

如果这也没有帮助,请选择您的项目,然后使用菜单项Source->Clean Up

回答by sl500059

I got referred here, because I had the same error. I am using maven on eclipse. I did right click on repo, chose build path->Conifgure build->Project References and checked the project references for my repo. This worked for me.

我在这里被提及,因为我有同样的错误。我在 Eclipse 上使用 Maven。我右键单击 repo,选择 build path->Conifgure build->Project References 并检查我的 repo 的项目引用。这对我有用。

回答by RCS

I was also getting the same error. In my case problem was, I had put same jar multiple times once through "user library" & next time through "build path" on the same Project. Just deleted the repeated jars from the classpath & got ride of the above error.

我也遇到了同样的错误。就我而言,问题是,我曾多次通过“用户库”和下一次通过同一项目的“构建路径”放置同一个 jar。刚刚从类路径中删除了重复的 jars 并解决了上述错误。

回答by Dkarode

I also had a different, degenerate case of this problem. Turned out, we had a class in our project that had a file (so Eclipse kept it on the classpath) but no actual class defined in the file (the file only had imports and a class comment... probably a merge gone wrong). Anyway, deleting the file solved the issue.

我也有一个不同的,这个问题的退化案例。原来,我们的项目中有一个类,它有一个文件(因此 Eclipse 将它保存在类路径中)但文件中没有定义实际的类(该文件只有导入和类注释......可能是合并出错了) . 无论如何,删除文件解决了问题。

回答by CONvid19

In my case, the classes were empty, and the compiler whined:

在我的例子中,类是空的,编译器抱怨:

Class files on classpath not found or not accessible for: 'ibDemo/src/com/ib/controller/LocationCode.java'
Class files on classpath not found or not accessible for: 'ibDemo/src/com/ib/controller/PairPanel.java'

To solve this I'd to add a class declaration:

为了解决这个问题,我要添加一个类声明:

public class LocationCode
{

}

and

public class PairPanel
{

}

回答by Mohan Kumar Kannan

I had the same error and after trying out multiple recommendations, nothing had worked out. So I created a new workspace and refer to this project. After that, it got successfully built and exported the JAR without errors.

我有同样的错误,在尝试了多个建议后,没有任何结果。所以我创建了一个新的工作区并参考了这个项目。之后,它成功构建并导出了 JAR,没有错误。

回答by Vaibhav Mishra

Not sure this might be the best possible solution, but do check java build path. I had it pointing to a wrong location because of which I was facing class not found error. Once java build path was fixed, the problem was resolved.

不确定这可能是最好的解决方案,但请检查 java 构建路径。我让它指向了一个错误的位置,因为我面临着 class not found 错误。一旦java构建路径被修复,问题就解决了。

回答by EdwardF

I came here on same error. In my case, nothing was compiling (building?) and Eclipse didn't tell me there was any issue with the build other than these cryptic messages. I eventually unzipped the jar file and saw that it had no classes in it. It was because because the project I referenced in my build path wasn't built. In my case, the project would not compile in a million years, but I had access to jar files from R&D dept who could and did compile it in their own way. So I referenced those jar files instead. Now my classes compile and the error went away. I'm sure I would have done that in the first place but "Helpful" Eclipse suggested for me to reference the unbuilt project so I went along with the bad suggestion!

我是因为同样的错误来到这里的。在我的情况下,没有编译(构建?)并且 Eclipse 没有告诉我除了这些神秘的消息之外构建有任何问题。我最终解压了 jar 文件,发现里面没有类。那是因为我在构建路径中引用的项目没有构建。就我而言,该项目不会在一百万年内编译,但我可以访问研发部门的 jar 文件,他们可以并确实以自己的方式编译它。所以我引用了那些 jar 文件。现在我的类编译并且错误消失了。我确定我首先会这样做,但是“有用”的 Eclipse 建议我参考未构建的项目,所以我同意了这个糟糕的建议!