Подтвердить что ты не робот

Eclipse - JAR creation failed "Файлы классов на пути к классам не найдены или недоступны для..."

У меня есть проект в 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 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();
                }
            }
        }    
}

Любые идеи о том, почему я не могу экспортировать/компилировать? У меня никогда не было этой проблемы раньше.

4b9b3361

Ответ 1

Просто выполните очистку и/или перестройте проект.

Вы можете найти его в меню Project Eclipse.

Ответ 2

У меня также был другой, вырожденный случай этой проблемы. Оказалось, что у нас был класс в нашем проекте, в котором был файл (поэтому Eclipse сохранил его на пути к классу), но в нем не было определенного класса (файл имел только импорт и комментарий к классу... вероятно, слияние не получилось), Во всяком случае, удаление файла решило проблему.

Ответ 3

Его довольно ненавистно, что Eclipse всегда генерирует скрытые файлы .project и .classpath в папке проекта. Иногда вы не знаете, если в этих файлах что-то не так.

После обновления вашего Eclipse и если вы нашли следующий компилятор error, Id предлагает вам проверить .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"/>

Глупое Eclipse приложило это без всякой причины. Просто удалите его чтобы он снова работал.;)

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

Источник: http://hochit.com/2006/07/06/eclipse-upgrading-problem-javalangobject-not-found/

Кроме того, вы можете проверить project settings в затмении. Щелкните правой кнопкой мыши свой проект и выберите свойства. Перейдите на Java Build Path и должна быть более конкретная информация о проблеме. Скорее всего, вы установите JDK в версию, которая не существует в новой системе.

Если это тоже не помогает, выберите свой проект, а затем используйте пункт меню Source->Clean Up.

Ответ 4

Я получил здесь, потому что у меня была такая же ошибка. Я использую maven на затмении. Я нажал правой кнопкой мыши на репо, выбрал путь сборки → Conifgure build- > Project References и проверил ссылки на проект для моего репо. Это сработало для меня.

Ответ 5

Я тоже получал ту же ошибку. В моем случае проблема была, я поставил один и тот же банку несколько раз один раз через "пользовательскую библиотеку" и в следующий раз через "путь сборки" в том же проекте. Просто удалил повторяющиеся баночки из пути к классам и получил прохождение вышеуказанной ошибки.

Ответ 6

В моем случае классы были пустыми, а компилятор ныл:

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'

Чтобы решить эту проблему, я бы добавил объявление класса:

public class LocationCode
{

}

и

public class PairPanel
{

}

Ответ 7

У меня была такая же ошибка, и после опроса нескольких рекомендаций ничего не получилось. Поэтому я создал новое рабочее пространство и ссылаюсь на этот проект. После этого он успешно создал и экспортировал JAR без ошибок.

Ответ 8

Не уверен, что это может быть наилучшим решением, но проверьте путь сборки java. У меня было это указание на неправильное местоположение, из-за которого я столкнулся с классом, не найденным ошибкой. Как только путь сборки java был исправлен, проблема была решена.

Ответ 9

Я пришел сюда по той же ошибке. В моем случае ничего не компилировалось (строилось?), И Eclipse не сказал мне, что есть какая-то проблема со сборкой, кроме этих загадочных сообщений. В конце концов я распаковал файл jar и увидел, что в нем нет классов. Это потому, что проект, на который я ссылался в моем пути сборки, не был построен. В моем случае проект не скомпилировался бы через миллион лет, но у меня был доступ к jar файлам из отдела исследований и разработок, которые могли и действительно скомпилировали его по-своему. Поэтому я ссылался на эти файлы JAR вместо. Теперь мои классы компилируются, и ошибка исчезла. Я уверен, что сделал бы это в первую очередь, но "Полезный" Eclipse предложил мне сослаться на не построенный проект, поэтому я согласился с плохим предложением!