JavaCompiler API error java.lang.NoClassDefFoundError when summoning the Cha/s Reflection API
-
The challenge is to use classes/objects in the dynamic class(s) from the rigid presentation.
javaFileContents
The challenge is to declare and further initiate facilities. After the line
System.out.println(Connector.class);
There is a mistake:java.lang.NoClassDefFoundError: controller/Connector
similar to the lines in the comments. It's clear that the mistake is because the compiler doesn't know about class. Connectorbut the package in which it is located is connected JavaCompiler API(parameter of optionList method getTask) and clearly importedimport controller.*;
♪ The way to jar'nick is a valid.pathToPackage
) In the event that the route is not correct, after the line passesimport controller.*;
andimport model.*;
Compiler, error is generated:/CompiledClass.java:4: error: package controller does not exist import controller.*; ^ /CompiledClass.java:5: error: package model does not exist import model.*; ^
Both packages are available at: C:\Users\leonid\AppData\Roaming\JDeveloper\system12.1.3.0.41.140521.1008\o.j2ee\drs\forum\ControllerEJB.jar, those ./controller and ./model and in these directories, subcompiled classes respectively.
That is, in the end, the compiler sees the package and successfully imports it into the classroom, but does not see the classes inside the package, the use of other classes/objects, standard java-lib, is incorrectly compiled, allowed after the line.
System.out.println(String.class)
There is no error and the result is good.Code:
public class CompilerJavaManager {
public static void compileJavaFileObject(StringBuilder inputString, Writer jspOut, String sessionId, String pathToPackage) throws Exception { String className = "CompiledClass"; String classMethod = "methodOf" + className; Class[] parameters = new Class[] { sessionId.getClass() }; Object[] arguments = new Object[] { sessionId }; Class compiledClass = null; //Class<?> c = Class.forName(className); StringBuilder javaFileContents = new StringBuilder("" + //"package compiled;" + '\n' + "import java.io.*;\n" + "import java.util.*;\n" + "import controller.*;\n" + "import model.*;\n" + '\n' + "public class " + className +"{\n" + " private Writer out = null;\n" + //" private Connector connector = null;\n" + //" private UPContainer container = null;\n" + //" private Controller controller = null;\n" + //" private userHandler handler = null;\n" + '\n' + " public " + className +"(Writer out){\n" + " this.out = out;\n" + " }\n" + '\n' + " public void " + classMethod + "(String sessionId) throws java.io.IOException{\n" + " System.out.println(Connector.class);" + //" Connector connector = Connector.getConnector();\n" + //" UPContainer container = Connector.getConnector().getContainerInstance(sessionId);\n" + //" Controller controller = container.getControllerInstance();\n" + //" userHandler handler = container.getUserHandlerInstance();\n" + //inputString + " }\n" + "}\n"); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector diagnosticsCollector = new DiagnosticCollector(); StandardJavaFileManager standardJavaFileManager = compiler.getStandardFileManager(diagnosticsCollector, null, null); SpecialClassLoader classLoader = new SpecialClassLoader(); SpecialJavaFileManager fileManager = new SpecialJavaFileManager(standardJavaFileManager, classLoader); List<String> optionList = new ArrayList<String>(); optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path") + ";" + pathToPackage)); JavaObjectFromString javaObjectFromString = new JavaObjectFromString(className, javaFileContents.toString()); Iterable fileObjects = Arrays.asList(javaObjectFromString); Iterable classes = null; Writer out = new PrintWriter(jspOut); CompilationTask task = compiler.getTask(out, fileManager, diagnosticsCollector, optionList, classes, fileObjects); Boolean result = task.call(); List<Diagnostic> diagnostics = diagnosticsCollector.getDiagnostics(); if (result) { try{ compiledClass = classLoader.findClass(className); Constructor<?> constructor = compiledClass.getConstructor(Writer.class); Object instance = constructor.newInstance(jspOut); Method instanceMethod = compiledClass.getDeclaredMethod(classMethod, parameters); instanceMethod.invoke(instance, arguments); } catch(java.lang.reflect.InvocationTargetException ex) { System.out.println(ex.getCause()); } } else { // Compilation fails for (Diagnostic d : diagnostics) { System.out.println(d); } } } private static class JavaObjectFromString extends SimpleJavaFileObject { private String sourceCode = null; public JavaObjectFromString(String className, String sourceCode) throws Exception { super(URI.create("file:///" + className + Kind.SOURCE.extension), Kind.SOURCE); this.sourceCode = sourceCode; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return sourceCode; } @Override public OutputStream openOutputStream() { throw new IllegalStateException(); } @Override public InputStream openInputStream() { return new ByteArrayInputStream(sourceCode.getBytes()); } } private static class JavaObjectFromByteCode extends SimpleJavaFileObject { private ByteArrayOutputStream baos; public JavaObjectFromByteCode(String className) { super(URI.create("byte:///" + className + Kind.CLASS.extension), Kind.CLASS); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { throw new IllegalStateException(); } @Override public OutputStream openOutputStream() { baos = new ByteArrayOutputStream(); return baos; } @Override public InputStream openInputStream() { throw new IllegalStateException(); } public byte[] getBytes() { return baos.toByteArray(); } } private static class SpecialClassLoader extends ClassLoader { private Map<String,JavaObjectFromByteCode> m = new HashMap<String, JavaObjectFromByteCode>(); protected Class<?> findClass(String className) throws ClassNotFoundException { JavaObjectFromByteCode jobc = m.get(className); if (jobc==null){ jobc = m.get(className.replace(".","/")); if (jobc==null){ return super.findClass(className); } } return defineClass(className, jobc.getBytes(), 0, jobc.getBytes().length); } public void addClass(String className, JavaObjectFromByteCode jobc) { m.put(className, jobc); } } private static class SpecialJavaFileManager extends ForwardingJavaFileManager { private SpecialClassLoader scl; public SpecialJavaFileManager(StandardJavaFileManager sjfm, SpecialClassLoader scl) { super(sjfm); this.scl = scl; } public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException { JavaObjectFromByteCode jobc = new JavaObjectFromByteCode(className); scl.addClass(className, jobc); return jobc; } public ClassLoader getClassLoader(Location location) { return scl; } }
}
In addition to 15.12.2015 14:56 (MCC):
Class code connector:
package controller;
import java.util.ArrayList;
import java.util.Hashtable;import java.util.Iterator;
import java.util.List;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;public class Connector {
private static Connector connector = null;
private static Context context = null;
private List<UPContainer> containers = new ArrayList<UPContainer>();public Connector() throws NamingException { context = getInitialContext(); } public static synchronized Connector getConnector() { try { if (connector == null) { connector = new Connector(); } } catch(Exception ex){ ex.printStackTrace(); } return connector; } public synchronized UPContainer getContainerInstance(String session) { UPContainer container = new UPContainer(); boolean has = false; try { Iterator iterator = containers.iterator(); while (iterator.hasNext()) { UPContainer ch = (UPContainer) iterator.next(); if (session.equalsIgnoreCase(ch.getSession())) { has = true; container = ch; break; } } if (!has) { container.setSession(session); container.setControllerInstance((Controller) context.lookup("forum-Controller-Controller#controller.Controller")); container.setUserHandlerInstance((userHandler) context.lookup("forum-Controller-userHandler#controller.userHandler")); containers.add(container); } } catch (Exception ex) { ex.printStackTrace(); } return container; } public synchronized boolean isActive(String userName) { try { Iterator iterator = containers.iterator(); while (iterator.hasNext()) { UPContainer ch = (UPContainer) iterator.next(); if (ch.getUserHandlerInstance().getUserCookie() != null) if (userName.equalsIgnoreCase(ch.getUserHandlerInstance().getUserCookie().getValue())) return true; } } catch (Exception ex) { ex.printStackTrace(); } return false; } public synchronized void destroyContainerInstance(String session) { try { Iterator iterator = containers.iterator(); while (iterator.hasNext()) { UPContainer ch = (UPContainer) iterator.next(); if (session.equalsIgnoreCase(ch.getSession())) { ch.setControllerInstance(null); ch.setUserHandlerInstance(null); containers.remove(ch); break; } } } catch (Exception ex) { ex.printStackTrace(); } } public synchronized int getAmountOfUsersOnline(boolean sm) { try { if (sm) { int counter = 0; Iterator iterator = containers.iterator(); while (iterator.hasNext()) { UPContainer ch = (UPContainer) iterator.next(); if (ch.getUserHandlerInstance().getUserCookie() != null) counter++; } return counter; } } catch (Exception ex) { ex.printStackTrace(); } return containers.size(); } public synchronized List<String> getOnlineUsers() { List usersList = new ArrayList(); try { Iterator iterator = containers.iterator(); while (iterator.hasNext()) { UPContainer ch = (UPContainer) iterator.next(); if (ch.getUserHandlerInstance().getUserCookie() != null) usersList.add(ch.getUserHandlerInstance().getUserCookie().getValue()); } } catch (Exception ex) { ex.printStackTrace(); } return usersList; } private Context getInitialContext() throws NamingException { Hashtable env = new Hashtable(); // WebLogic Server 10.x/12.x connection details env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101"); return new InitialContext(env); }
}
Supplement of 15:49:
Class code Controller:
package controller;
import model.Categories;
import model.Threads;public class pageController {
private int topicsPerPage = 15;
private int viewsPages = 5;
private int currentPage = 0;
private int currentAmountPages = 0;
private int amountPages = 0;
private int tagCloudlinks = 20;public pageController() { } public void setDefaultTopicsPerPage(int perPage) { topicsPerPage = perPage; } public int getDefaultTopicsPerPage() { return topicsPerPage; } public int getPagesLimit() { return viewsPages; } public void setPagesLimit(int viewsLimit) { viewsPages = viewsLimit; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(String page) { currentPage = page != null && page != "" ? Integer.parseInt(page) : 0; } public int getCurrentAmountPages() { return currentAmountPages; } public void setCurrentAmountPages(int size) { setAmountPages(size); currentAmountPages = (int)Math.ceil(new Long(size).doubleValue()/new Long(topicsPerPage).doubleValue()); } public void setAmountPages(int amount) { amountPages = amount; } public int getAmountPages() { return amountPages; } public void setAmountCloudLinks(int amount) { tagCloudlinks = amount; } public int getAmountCloudLinks() { return tagCloudlinks; }
}
UPDATE
The problem is still unsolved, the waste of time makes me crazy, put in a package controller, with classes where only classpath can be indicated wherever it is possible, but there's still a mistake.
java.lang.NoClassDefFoundError: controller/Connector
♪If a separate annex with the above classes is established, the compilation is successfully completed
System.out.println(Connector.class);
Turns out the conjector class, as it was necessary, but if it starts through JSP, the problem described above arises.The whole idea of this: a request for an OBD code (Java,PHP,HTML) - state parsing of the whole case--- in JSP compilation challenge - state-readable HTML code in JSP
-
Cause of error NoClassDefFoundError varies greatly, behind the root causes of the problem. In my case, the error is related to the reloading of class loaders and the visibility area of other class loaders (see cm) Class loading hierarchyOne of the loaders is trying to find the right class at their level but does not find it here, and the request for a higher loader(s) is further downloaded at a higher level, but on the other hand, the necessary class is to be arranged by another loader(s) when compiling the class(s) from the rigid presentation. StringBuilder Class CompiledClass) and there's an error in it.
Specifically: in jsp(Web App) classes are downloaded, but since they are not known at this level of loaders, the loader at this level is delegated to the above load levels and, in consequence, Java EE App(s) is downloaded. On the other hand, the submersion occurs at a different level with CompiledClass and errors occur. The two loaders are loaded with the same classes.
Why is it successfully compiled in a separate annex? As described above, the compilation has been successful. Why? Answer: Classes are loaded with only one loader and no exceptions to the ratio.
The request not to edit the message was not solved by the end of the communication (not yet decided) in the event of a more precise specific response.
How can we try? Reflexion(not yet checked) in the compilable class(s) but there's one thing, but it's clear that when the "complicity" of the class comes up, it's gonna have to sign a lot of lines of the code, which is why it's not quite appropriate.