I wrote my classloader:
package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class PluginManager extends ClassLoader {
private final String pluginRootDirectory;
public PluginManager(String pluginRootDirectory) {
this.pluginRootDirectory = pluginRootDirectory;
}
public Plugin load(String pluginName, String pluginClassName) {
String name = pluginName + "." + pluginClassName;
try {
Class clazz;
try {
clazz = super.findSystemClass(name);
} catch (ClassNotFoundException e) {
String fileName = pluginRootDirectory + "\\" + pluginName + "\\" + pluginClassName + ".class";
try (FileInputStream fin = new FileInputStream(fileName)) {
byte[] buffer = new byte[(int) (new File(fileName).length())];
fin.read(buffer);
clazz = defineClass(name, buffer, 0, buffer.length);
}
}
return (Plugin)clazz.newInstance();
} catch (IOException | InstantiationException | IllegalAccessException ignored) {
return null;
}
}
}
When I run it:
package ru.sberbank.school.homework8;
import ru.sberbank.school.homework8.plugin.Plugin;
public class PluginManagerTest {
public static void main(String[] args) {
String pluginRootDirectory = "D:\\sbt\\target\\classes\\ru\\sberbank\\school\\homework8";
PluginManager pluginManager = new PluginManager(pluginRootDirectory);
Plugin plugin = pluginManager.load("plugin", "PluginImpl");
if (plugin != null) {
plugin.doUseful();
}
}
}
Exception in thread "main" java.lang.NoClassDefFoundError:
plugin/PluginImpl (wrong name:
ru/sberbank/school/homework8/plugin/PluginImpl) at
java.lang.ClassLoader.defineClass1(Native Method)
I get NoClassDefFoundError. Why??? How can I fix it???
Help me, please!
package ru.sberbank.school.homework8.plugin;
public class PluginImpl implements Plugin {
#Override
public void doUseful() {
System.out.println("My plugin!");
}
}
You get this error because you don't provide the correct FQN of your class, indeed in your load method, you try to find the class corresponding to pluginName + "." + pluginClassName that will be in your case plugin.PluginImpl but the package name of your class PluginImpl is actually ru.sberbank.school.homework8.plugin such that the real FQN of your class is ru.sberbank.school.homework8.plugin.PluginImpl.
To fix this problem, you need to replace:
Plugin plugin = pluginManager.load("plugin", "PluginImpl");
With:
Plugin plugin = pluginManager.load("ru.sberbank.school.homework8.plugin", "PluginImpl");
Or you could modify your method load to add a prefix assuming that you will always retrieve your plugins from the same root package:
public Plugin load(String pluginName, String pluginClassName) {
String name = "ru.sberbank.school.homework8." + pluginName + "." + pluginClassName;
Related
I have a Jar in java which is containing 2 classes and 1 Interface. How can i get the interface and class names from the jar. Currently I am able to get the class names, but not the interface name.
List jClasses = getClasseNames("D://Test.jar");
System.out.println(jClasses.size());
for (int i = 0; i < jClasses.size(); i++) {
System.out.println("Print Classes ::" + jClasses.get(i));
if(( null != jClasses.getClass().getInterfaces()[i])) {
System.out.println(jClasses.getClass().getInterfaces()[i]);
} else {
System.out.println("No connection");
}
}
public static List getClasseNames(String jarName) {
ArrayList classes = new ArrayList();
try {
JarInputStream jarFile = new JarInputStream(new FileInputStream(
jarName));
JarEntry jarEntry;
while (true) {
jarEntry = jarFile.getNextJarEntry();
if (jarEntry == null) {
break;
}
if (jarEntry.getName().endsWith(".class")) {
classes.add(jarEntry.getName().replaceAll("/", "\\."));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return classes;
}
output :
Print Classes ::com.java.testclient.PTest1.class
interface java.util.List
======
Print Classes ::com.java.testclient.ClassSpy.class
interface java.util.RandomAccess
======
Print Classes ::com.java.testclient.myInt.class
interface java.lang.Cloneable
======
Print Classes ::com.java.testclient.PTest.class
interface java.io.Serializable
Please suggest.
You can use this class:
package io.github.gabrielbb.java.utilities;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
/**
* #author Gabriel Basilio Brito
* #since 12/26/2016
* #version 1.1
*/
public class ClassesAndInterfacesFromJar {
public static List<Class> getJarClasses(String jarPath) throws IOException, ClassNotFoundException {
File jarFile = new File(jarPath);
return getJarClasses(jarFile);
}
public static List<Class> getJarClasses(File jar) throws IOException, ClassNotFoundException {
ArrayList<Class> classes = new ArrayList();
JarInputStream jarInputStream = null;
URLClassLoader cl;
try {
cl = URLClassLoader.newInstance(new URL[]{new URL("jar:file:" + jar + "!/")}); // To load classes inside the jar, after getting their names
jarInputStream = new JarInputStream(new FileInputStream(
jar)); // Getting a JarInputStream to iterate through the Jar files
JarEntry jarEntry = jarInputStream.getNextJarEntry();
while (jarEntry != null) {
if (jarEntry.getName().endsWith(".class")) { // Avoiding non ".class" files
String className = jarEntry.getName().replaceAll("/", "\\."); // The ClassLoader works with "." instead of "/"
className = className.substring(0, jarEntry.getName().length() - 6); // Removing ".class" from the string
Class clazz = cl.loadClass(className); // Loading the class by its name
classes.add(clazz);
}
jarEntry = jarInputStream.getNextJarEntry(); // Next File
}
} finally {
if (jarInputStream != null) {
jarInputStream.close(); // Closes the FileInputStream
}
}
return classes;
}
// Main Method for testing purposes
public static void main(String[] args) {
try {
String jarPath = "C://Test.jar";
List<Class> classes = getJarClasses(jarPath);
for (Class c : classes) {
// Here we can use the "isInterface" method to differentiate an Interface from a Class
System.out.println(c.isInterface() ? "Interface: " + c.getName() : "Class: " + c.getName());
}
} catch (Exception ex) {
System.err.println(ex);
}
}
It can be found at:
https://github.com/GabrielBB/Java-Utilities/blob/master/ClassesAndInterfacesFromJar.java
I'm writing a plugin loader -- it loads jars that are not on the classpath. I wrote a simple custom ClassLoader that takes a JarFile in its constructor and looks in the JarFile for the named class. This loader simply overrides the findClass() method of ClassLoader, and works fine.
Then I determined that I also needed to be able to get resources from the plugin jar. So I overrode findResource(). This had the unexpected result of causing the base plugin class to not be able to find other classes in the jar: I get NoClassDefFoundErrors!
In other words, if I have plugin.jar that contains MyPlugin and MyPluginComponent:
if I do not override findResource(), then I can load the jar, create an instance of MyPlugin, and that in turn can create a MyPluginComponent. However I cannot find resources that are bundled in the jar.
if I do override findResource(), then I can load the jar, create an instance of MyPlugin, but if MyPlugin attempts to create a MyPluginComponent, I get a NoClassDefFoundError.
This suggests that somehow the implementation of findResource() is unable to find class files -- but it's not even getting called (per my logging), so I don't see how that could be the case. How does this interaction work out, and how do I fix it?
I tried to write a small self-contained example, and ran into difficulty manually generating a jar file that wouldn't produce "incompatible magic number" errors. Hopefully whatever I'm doing wrong will be evident from the class loader alone. Sorry for the inconvenience, and thank you for your time.
import com.google.common.io.CharStreams;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.ClassLoader;
import java.net.URL;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Custom class loader for loading plugin classes. Adapted from
* http://kalanir.blogspot.com/2010/01/how-to-write-custom-class-loader-to.html
*/
public static class PluginLoader extends ClassLoader {
private JarFile jarFile_;
public PluginLoader(JarFile jarFile) {
super(Thread.currentThread().getContextClassLoader());
jarFile_ = jarFile;
}
#Override
public Class findClass(String className) {
try {
// Replace "." with "/" for seeking through the jar.
String classPath = className.replace(".", "/") + ".class";
System.out.println("Searching for " + className + " under " + classPath);
JarEntry entry = jarFile_.getJarEntry(classPath);
if (entry == null) {
return null;
}
InputStream stream = jarFile_.getInputStream(entry);
String contents = CharStreams.toString(
new InputStreamReader(stream));
stream.close();
byte[] bytes = contents.getBytes();
Class result = defineClass(className, bytes, 0, bytes.length);
return result;
}
catch (IOException e) {
System.out.println(e + "Unable to load jar file " + jarFile_.getName());
}
catch (ClassFormatError e) {
System.out.println(e + "Unable to read class data for class " + className + " from jar " + jarFile_.getName());
}
return null;
}
#Override
protected URL findResource(String name) {
System.out.println("Asked to find resource at " + name);
try {
String base = new File(jarFile_.getName()).toURI().toURL().toString();
URL result = new URL(String.format("jar:%s!/%s", base, name));
System.out.println("Result is " + result);
return result;
}
catch (IOException e) {
System.out.println(e + "Unable to construct URL to find " + name);
return null;
}
}
#Override
public InputStream getResourceAsStream(String name) {
System.out.println("Getting resource at " +name);
JarEntry entry = jarFile_.getJarEntry(name);
if (entry == null) {
System.out.println("Couldn't find resource " + name);
return null;
}
try {
return jarFile_.getInputStream(entry);
}
catch (IOException e) {
System.out.println(e + "Unable to load resource " + name + " from jar file " + jarFile_.getName());
return null;
}
}
}
If your requirement is to just read extra JAR files extending URLClassLoader might be a better option.
public class PluginLoader extends URLClassLoader {
public PluginLoader(String jar) throws MalformedURLException {
super(new URL[] { new File(jar).toURI().toURL() });
}
}
Ich have wrote a little module system, where modules are packaged into jars.
The application has to load these modules at start.
For loading these jars and extract the classes which implements the IModule interface or extends the Module class, i have written an ModuleLoader, by inspiring an tutorial.
The class Module is also implementing the IModule interface.
Now, if i start the application, there is thrown an exception.
IModuleLoader moduleLoader = new DefaultModuleLoader();
List<IModule> moduleList = moduleLoader.loadModulesFromDir(moduleDir);
Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: com/corundumstudio/socketio/AuthorizationListener
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at com.jukusoft.jbackendengine.backendengine.module.impl.DefaultModuleLoader.extractClassesFromJAR(DefaultModuleLoader.java:137)
at com.jukusoft.jbackendengine.backendengine.module.impl.DefaultModuleLoader.extractClassesFromJARs(DefaultModuleLoader.java:120)
at com.jukusoft.jbackendengine.backendengine.module.impl.DefaultModuleLoader.loadModulesFromDir(DefaultModuleLoader.java:43)
at com.jukusoft.jbackendengine.backendengine.module.impl.DefaultModuleManager.loadModulesFromDir(DefaultModuleManager.java:91)
at com.jukusoft.jbackendengine.backendengine.module.impl.DefaultModuleManager.loadAndStart(DefaultModuleManager.java:100)
at com.jukusoft.jbackendengine.backendengine.builder.DefaultBackendEngineBuilder.buildBackendEngine(DefaultBackendEngineBuilder.java:26)
at com.jukusoft.jbackendengine.backendengine.builder.DefaultBackendEngineBuilder.buildBackendEngine(DefaultBackendEngineBuilder.java:16)
at com.jukusoft.jbackendengine.backendengine.factory.BackendEngineFactory.createNewDefaultBackendEngine(BackendEngineFactory.java:22)
at com.jukusoft.jbackendengine.backendengine.ServerEngineMain.main(ServerEngineMain.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.ClassNotFoundException: com.corundumstudio.socketio.AuthorizationListener
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 25 more
Here is the code of class ModuleLoader:
package com.jukusoft.jbackendengine.backendengine.module.impl;
import com.jukusoft.jbackendengine.backendengine.module.IModule;
import com.jukusoft.jbackendengine.backendengine.module.IModuleLoader;
import com.jukusoft.jbackendengine.backendengine.module.ModuleUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
/**
* Created by Justin on 03.07.2015.
*/
public class DefaultModuleLoader implements IModuleLoader {
#Override
public List<IModule> loadModulesFromDir(File modulesDir) throws IOException {
FilenameFilter filenameFilter = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".jar") || name.endsWith(".jam");
}
};
if (!modulesDir.exists()) {
System.out.println("directory modules doesnt exists, creating directory modules.");
modulesDir.mkdirs();
}
File[] files = modulesDir.listFiles(filenameFilter);
System.out.println("" + files.length + " .jar files in directory " + modulesDir.getAbsolutePath() + " found.");
ClassLoader classLoader = new URLClassLoader(fileArrayToURLs(files));
List<Class<IModule>> moduleClasses = extractClassesFromJARs(files, classLoader);
System.out.println("" + moduleClasses.size() + " modules found.");
return createModuleObjects(moduleClasses);
}
#Override
public List<IModule> loadModulesFromFile(File moduleFile) throws IOException {
ClassLoader classLoader = new URLClassLoader(fileToURL(moduleFile));
List<Class<IModule>> moduleClasses = extractClassesFromJAR(moduleFile, classLoader);
return createModuleObjects(moduleClasses);
}
private URL[] fileArrayToURLs (File[] files) throws MalformedURLException {
URL[] urlsArray = new URL[files.length];
for (int i = 0; i < files.length; i++) {
urlsArray[i] = files[i].toURI().toURL();
}
return urlsArray;
}
private URL[] fileToURL (File file) throws MalformedURLException {
URL[] urlsArray = new URL[1];
urlsArray[0] = file.toURI().toURL();
return urlsArray;
}
public boolean isModuleClass (Class<?> cls) {
//System.out.println("isModuleClass() " + cls.getName() + ".");
/*try {
for (Class<?> cls1 : cls.getInterfaces()) {
System.out.println("Found interface " + cls1.getName() + " in class " + cls.getName() + ".");
if ((cls1.equals(IModule.class) || cls1.equals(Module.class)) && ModuleUtils.containsModuleInfo(cls)) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}*/
return IModule.class.isAssignableFrom(cls) || Module.class.isAssignableFrom(cls);
}
public IModule createModuleObject (Class<IModule> moduleClass) throws IllegalAccessException, InstantiationException {
return moduleClass.newInstance();
}
private List<IModule> createModuleObjects(List<Class<IModule>> classList) {
List<IModule> modules = new ArrayList<IModule>(classList.size());
for (Class<IModule> module : classList) {
try {
modules.add(module.newInstance());
} catch (InstantiationException e) {
System.err.println("Cannot create new instance of class " + module.getName() + ".");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.err.println("IllegalAccess for module: " + module.getName() + ".");
e.printStackTrace();
}
}
return modules;
}
private List<Class<IModule>> extractClassesFromJARs(File[] jars, ClassLoader cl) throws IOException {
List<Class<IModule>> classList = new ArrayList<Class<IModule>>();
for (File jar : jars) {
classList.addAll(extractClassesFromJAR(jar, cl));
}
return classList;
}
#SuppressWarnings("unchecked")
private List<Class<IModule>> extractClassesFromJAR(File jarFile, ClassLoader classLoader) throws IOException {
List<Class<IModule>> classList = new ArrayList<Class<IModule>>();
JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
JarEntry ent = null;
while ((ent = jarInputStream.getNextJarEntry()) != null) {
if (ent.getName().toLowerCase().endsWith(".class")) {
try {
Class<?> cls = classLoader.loadClass(ent.getName().substring(0, ent.getName().length() - 6).replace('/', '.'));
if (isModuleClass(cls)) {
classList.add((Class<IModule>) cls);
}
} catch (ClassNotFoundException e) {
System.err.println("Cannot load class " + ent.getName() + ".");
//e.printStackTrace();
}
}
}
jarInputStream.close();
return classList;
}
}
the difference between ClassNotFoundException and NoClassDefFoundError are that the first happens because the named class can't be found on the classpath, the second (which is what you have) occurs when a class can be found but that some other error happens when the class is loaded. With this in mind perhaps there's a static piece of code or initialised member variable that's causing an exception. I have a vague recollection that a class I had once caused this error because I declared and initialised a variable to a resource that at runtime was null i.e. InputStream in = blah.class.getResourceAsStream(..blah...) so when my class that had in as a member was loaded it threw an NPE.
Helps if I actually read the whole stack trace before answering, yes the def error is caused by the ClassNotFoundException which makes things easier it just means that Authorization class isn't accessible on the classpath
Is
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
</dependency>
present in your maven pom.xml?
If yes, try to add corresponding netty-socketio***.jar to classpath where your run your program.
I have been playing around with a CustomerClassLoader as i am trying to load a .class file into JUnitCore.runClasses(...); but i am getting the following error
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: SimpleTest (wrong name: JUnit/SimpleTest)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at Java.CustomClassLoader.access$000(CustomClassLoader.java:16)
at Java.CustomClassLoader$1.run(CustomClassLoader.java:45)
at java.security.AccessController.doPrivileged(Native Method)
at Java.CustomClassLoader.findClass(CustomClassLoader.java:33)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
.....
I don't know what it wrong as I am passing in the correct class name and path for the class. here is the code that i am using
CustomClassLoader
import java.io.FileInputStream;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
public class CustomClassLoader extends ClassLoader {
String repoLocation = "C:/TempBINfolder/bin/JUnit/";
public CustomClassLoader() { }
public CustomClassLoader(ClassLoader parent) {
super(parent);
}
#Override
protected Class<?> findClass(final String name)
throws ClassNotFoundException {
AccessControlContext acc = AccessController.getContext();
try {
return (Class)AccessController.doPrivileged(
new PrivilegedExceptionAction() {
public Object run() throws ClassNotFoundException {
FileInputStream fi = null;
try {
String path = name.replace('.', '/');
fi = new FileInputStream(repoLocation + path
+ ".class");
byte[] classBytes = new byte[fi.available()];
fi.read(classBytes);
return defineClass(name, classBytes, 0,
classBytes.length);
}catch(Exception e )
{
throw new ClassNotFoundException(name);
}
}
}, acc);
} catch (java.security.PrivilegedActionException pae) {
return super.findClass(name);
}
}
}
And this is how i am calling it
ClassLoader cls= new CustomClassLoader(ClassLoader.getSystemClassLoader());
Class stringClass = null;
try {
stringClass = cls.loadClass("SimpleTest");
} catch (ClassNotFoundException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
}
try {
stringClass.newInstance();
} catch (InstantiationException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(CompilerForm.class.getName()).log(Level.SEVERE, null, ex);
}
JUnitCore.runClasses(stringClass);
Does anyone know why i am getting this error?
Change
stringClass = cls.loadClass("SimpleTest");
to
stringClass = cls.loadClass("JUnit.SimpleTest");
(i.e Add the fully qualified package name of the class file)
and
String repoLocation = "C:/TempBINfolder/bin/JUnit/";
to
String repoLocation = "C:/TempBINfolder/bin/";
You must be declaring your SimpleTest class to be in JUnit package, but you are trying to load is as simply SimpleTest (no package). Try eiteher:
remove the package declaration
remove Junit from location: String repoLocation = "C:/TempBINfolder/bin/";
Class name should be fully qualified junit.samples.SimpleTest
stringClass = cls.loadClass("SimpleTest");
should be
stringClass = cls.loadClass("junit.sample.SimpleTest");
Sometimes this happens to me, and usually it's solved by a clean and build. If that doesn't work, I usually restart my IDE.
I have implemented a simple plugin based application with Java. Main plugin class is derived from and abstract class called "Plugin". The application reads that class from JAR file and runs the plugin by creating an instance of the class. Standard procedure I guess :)
Everything forks fine until now. But the problem occurs when I include a library to my plugin, like MySQL Connector. The exception NoClassDefFoundError and ClassNotFoundException are thrown after execution. I am overcoming the problem by adding MySQL connector library to the main application but what is the point then? :)
I am not a Java expert so I am not sure of any alternative solutions like defining a classpath for libraries etc.
Here is my plugin loader:
http://pastebin.com/90rQ9NfJ
And here is my plugin base class:
http://pastebin.com/Juuicwkm
I am executing from a GUI:
private void jButtonAddActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("JTask Plugin (*.JAR)", "JAR"));
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
File pluginFile = fileChooser.getSelectedFile();
PluginLoader pluginLoader = new PluginLoader();
Plugin plugin = pluginLoader.loadPlugin(pluginFile);
if (plugin != null)
jPanelPlugins.add(new PluginControl(jPanelPlugins, plugin));
}
}
You should really include your source code as well.
How are you executing the class i.e. via command line or from a GUI? If from the command line, then the MySQLConnector libraries, along with any other dependent library must be included in the classpath (java -classpath). The top answer to this question should help you- Java: how to import a jar file from command line
if the case, your class is a Mysql Driver you have to exclude (at the time the class is calling) classes that are not available. In the Folder of your .jar file there is one with the name "integration" it contains "jboss" and "c3p0" which are not present at this time.
while (en.hasMoreElements()) {
JarEntry entry = new JarEntry(en.nextElement());
String name = entry.getName();
if (name.contains("/integration/")) {
continue;
} else {
if (!entry.isDirectory() && name.toLowerCase().endsWith(".class"))
{
classList.add(name.replace(".class", ""));
}
}
}
This should load a mysql.xxx.jar file.
Try This
dynamicload.java
package dynamicloading;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
*
* #author Administrator
*/
class com_mysql_jdbc_Driver implements Driver {
private Driver driver;
com_mysql_jdbc_Driver(Driver cmjd) {
this.driver = cmjd;
}
#Override
public boolean acceptsURL(String aurlS) throws SQLException {
return this.driver.acceptsURL(aurlS);
}
#Override
public Connection connect(String aurlS, Properties pP) throws SQLException {
return this.driver.connect(aurlS, pP);
}
#Override
public int getMajorVersion() {
return this.driver.getMajorVersion();
}
#Override
public int getMinorVersion() {
return this.driver.getMinorVersion();
}
#Override
public DriverPropertyInfo[] getPropertyInfo(String aurlS, Properties pP) throws SQLException {
return this.driver.getPropertyInfo(aurlS, pP);
}
#Override
public boolean jdbcCompliant() {
return this.driver.jdbcCompliant();
}
}
public class DynMain {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
/* please set to your path*/
File file = new File("U:/mozsamples/mysql-connector-java-5.1.19-bin.jar");
Driver cmjdD;
String aktCS;
String urlS = "jdbc:mysql://localhost/db";
String userS = "must-be-set";
String passS = "must-be-set";
Connection con;
Statement stmt;
URLClassLoader clazzLoader = URLClassLoader.newInstance(new URL[]{file.toURI().toURL()});
JarFile jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry element = entries.nextElement();
if (element.getName().endsWith(".class")) {
String name = element.getName();
if (name.contains("/integration/")) {
System.out.println( "ignored: " + name );
continue;
} else
{
try {
aktCS = element.getName().replaceAll(".class", "").replaceAll("/", ".");
clazzLoader.loadClass(aktCS);
if (name.contains("com/mysql/jdbc/Driver")) {
cmjdD = (Driver)Class.forName(aktCS, true, clazzLoader).newInstance();
try {
DriverManager.registerDriver(new com_mysql_jdbc_Driver(cmjdD));
System.out.println( "register Class: " + aktCS );
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
try {
con = DriverManager.getConnection(urlS,userS,passS);
stmt = con.createStatement();
/*ResultSet rs = stmt.executeQuery("select * from idcart where ID=255"); */
stmt.close();
} catch (SQLException esql) {
esql.printStackTrace();
}
int j=0 ;
System.out.println("loaded Driver----------------------------------");
for( Enumeration en = DriverManager.getDrivers() ; en.hasMoreElements() ; j++)
System.out.println( en.nextElement().getClass().getName() );
if (j==0) { System.out.println("Driverlist empty"); }
System.out.println("-----------------------------------------------");
}
}
Output:
register Class: com.mysql.jdbc.Driver
ignored: com/mysql/jdbc/integration/c3p0/MysqlConnectionTester.class
ignored: com/mysql/jdbc/integration/jboss/ExtendedMysqlExceptionSorter.class
ignored: com/mysql/jdbc/integration/jboss/MysqlValidConnectionChecker.class
loaded Driver----------------------------------
sun.jdbc.odbc.JdbcOdbcDriver
dynamicloading.com_mysql_jdbc_Driver
-----------------------------------------------
OK ???