Thursday, 16 June 2016

[JDBC] How to find classes implemented java.sql.Drvier in JDBC Driver jar file.(JDBC 드라이버 Jar 파일에서 Drvier Class 찾기)


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public static java.util.List< String> findDriverClassNamesInJars( java.io.File[] jarFiles) throws FileNotFoundException, IOException {
  java.util.jar.JarInputStream jarFileInputStream = null;
  java.util.jar.JarEntry jarEntry = null;
  java.net.URLClassLoader ucl = null;
  java.net.URL url = null;
  ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  Class< ?> baseInClass = java.sql.Driver.class;
  java.util.List< String> classNames = new java.util.ArrayList< String>();
  
  for ( int ll = 0; ll < jarFiles.length; ll++) {
   url = new java.net.URL( "jar:file:" + jarFiles[ ll] + "!/");
   ucl = new URLClassLoader( new java.net.URL[] { url }, classLoader);
   try {
    jarFileInputStream =  new java.util.jar.JarInputStream( new java.io.FileInputStream( jarFiles[ ll]));
  
    while ( ( jarEntry = jarFileInputStream.getNextJarEntry()) != null) {
              if ( jarEntry.getName().endsWith( ".class")) {
                  String classname = jarEntry.getName().replaceAll( "/", "\\.");
                  classname = classname.substring( 0, classname.length() - 6);
                  if ( !classname.contains( "$")) {
                      try {
                          final Class< ?> myLoadedClass = Class.forName( classname, true, ucl);
                          if ( baseInClass.isAssignableFrom( myLoadedClass)) {
                           classNames.add( myLoadedClass.getName());
                          }
                      
                      } catch ( Exception e) {
                       continue;
 
                      } catch ( Error e) {
                       continue;
                       
                      }
                  }
              }
          }
   
   } finally {
    try {
     jarFileInputStream.close();
    } catch ( Exception e) {}
   }
  }
  
  return classNames;
        
 }

No comments:

Post a Comment