Friday, February 24, 2006

How to load subclass(es) from your jar file

Mr. Endy Muhardin found problems in finding and loading classes when developing his opensource application. Hope this code will help him. Ganbatte Mas Endy!!

Here is a simple code to illustrate how to load one or more subclass(es) from a jar file.

/*
* Created on Feb 24, 2006
*
*/
package com.monn;

import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
* @author Monang Setyawan
*
*/
public class Executor {
    
    public static void main(String[] args) throws Exception {
        new Executor().run();
        System.exit(0);
    }
    
    public void run() throws Exception {
        JFileChooser chooser = new JFileChooser();
        
        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            String parent;
            
            if ((parent = JOptionPane.showInputDialog(null,
            "superclass/interface name")) != null) {
                File file = chooser.getSelectedFile();
                
                URL jarUrl = new URL("jar:file:" + file.getAbsolutePath()
                + "!/");
                JarFile jarFile = ((JarURLConnection) jarUrl.openConnection())
                .getJarFile();
                
                URL[] urls = { file.toURL() };
                URLClassLoader loader = URLClassLoader.newInstance(urls, Thread
                .currentThread().getContextClassLoader());
                
                List nameList = getClassNames(jarFile);
                for (Iterator iter = nameList.iterator(); iter.hasNext();) {
                    String classname = (String) iter.next();
                    Class clazz = loader.loadClass(classname);
                    if (Class.forName(parent).isAssignableFrom(clazz)) {
                        // you've got your class
                        System.out.println(clazz);
                    }
                }
                
            }
        }
        
    }
    
    private List getClassNames(JarFile jarFile) {
        
        List nameList = new ArrayList();
        for (Enumeration enum = jarFile.entries(); enum.hasMoreElements();) {
            
            JarEntry entry = (JarEntry) enum.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class")) {
                int startPos = entryName.lastIndexOf('.');
                String shortName = entryName.substring(0, startPos);
                shortName = shortName.replace('/', '.').replace('\\', '.');
                nameList.add(shortName);
            }
        }
        
        return nameList;
        
    }
}



For simple test, you can select any JDBC driver jar file and type in "java.sql.Connection". My code above will try to find any implementations of Connection interface in your jar file.

permaLink() | postComments() | read10Comments()

Great work!
[url=http://ckiyhpta.com/ymip/iyth.html]My homepage[/url] | [url=http://xamgovhn.com/xnas/ubji.html]Cool site[/url]

By Anonymous Anonymous, at 11:18 PM  

Thank you!
My homepage | Please visit

By Anonymous Anonymous, at 11:18 PM  

Good design!
http://ckiyhpta.com/ymip/iyth.html | http://pvctifmd.com/nqst/kcod.html

By Anonymous Anonymous, at 11:19 PM  

Hello!

Nice site, keep up the good work .

http://buy-phentermine.hem.nu BUY PHENTERMINE
BUY PHENTERMINE
http://buy-phentermine.hem.nu buy phentermine
http://buy-phentermine.hem.nu phentermine online
http://buy-phentermine.hem.nu order phentermine
http://buy-phentermine.hem.nu cheap phentermine
http://buy-phentermine.hem.nu buy phentermine online
http://buy-phentermine.hem.nu phentermine diet pill
http://buy-phentermine.hem.nu phentermine online pharmacy
http://buy-phentermine.hem.nu phentermine prescription
http://buy-phentermine.hem.nu what is phentermine
http://buy-phentermine.hem.nu free phentermine

By Anonymous Anonymous, at 11:53 AM  

Latest news. Viagra, cialis

viagra
cialis
tramadol

By Anonymous Anonymous, at 2:50 PM  

Hello!

Nice site, keep up the good work .

http://buy-phentermine.hem.nu BUY PHENTERMINE
BUY PHENTERMINE
http://blogg.sol.no/buy-phentermine
BUY PHENTERMINE
http://s-url.net/0mzj/ PARISEXPOSED
http://s-url.net/0n21/ PARISEXPOSED COM
http://s-url.net/0n22/ FREE PARIS HILTON EXPOSED
http://s-url.net/0n23/ FREE ACCESS TO PARISEXPOSED
http://s-url.net/0n24/ FREE LOGINS TO PARISEXPOSED
http://s-url.net/0n25/ PARIS EXPOSED
http://s-url.net/0n26/ PARIS EXPOSED COM
http://s-url.net/0n27/ FREE CLIPS OF PARISEXPOSED MOVIES
http://s-url.net/0n28/ FREE CLIPS OF PARISEXPOSED PRIVATE VIDEO COLLECTION
http://s-url.net/0n29/ FREE CLIPS OF PARISEXPOSED LESBIAN VIDEOS
http://s-url.net/0n2b FREE CLIPS OF PARISEXPOSED DRUNK VIDEOS AND MOVIES
http://s-url.net/0n2c/ PARIS LEBIAN MOVIE
http://s-url.net/0n2d/ DOWNLOAD PARIS PRIVATE MOVIE COLLECTION
http://s-url.net/0n2e/ DOWNLOAD PARIS HILTON LESBIAN VIDEO
http://s-url.net/0n2f/ DOWNLOAD PARIS HILTON PRIVATE MOVIE COLLECTION
http://s-url.net/0n2g/ DOWNLOAD PARIS HILTON NEVER SEEN BEFORE SEX MOVIES

By Anonymous Anonymous, at 8:31 PM  

http://prieslar.info/?search=Jolanta+Lothe
http://prieslar.info/?search=www+gry+pl+cat177_1+html
http://prieslar.info/?search=Estampie
http://prieslar.info/?search=mittal+steel
http://prieslar.info/?search=britney+spears+christmas
http://prieslar.info/?search=tvn+turbo+w

By Blogger alex, at 1:30 PM  

http://prieslar.info/?search=Wielkie+nadzieje
http://prieslar.info/?search=kurnik+pl+358
http://prieslar.info/?search=darmowe+sex+filmy
http://prieslar.info/?search=muzyka+organowa
http://prieslar.info/?search=smieszne+filmiki.pl
http://prieslar.info/?search=cartoon

By Blogger alex, at 3:12 PM  

http://prieslar.info/?search=Osnowa+geodezyjna
http://prieslar.info/?search=impreza+andrzejkowa
http://prieslar.info/?search=Bariera+wysokosciowa
http://prieslar.info/?search=Teatr+sredniowiecza
http://prieslar.info/?search=ginekolodzy+i+poloznicy
http://prieslar.info/?search=sow

By Blogger alex, at 4:57 PM  

http://prieslar.info/?search=filmy+pl
http://prieslar.info/?search=bajki
http://prieslar.info/?search=dziecko+allegro
http://prieslar.info/?search=Bruityzm
http://prieslar.info/?search=taniec
http://prieslar.info/?search=przedszkole

By Blogger alex, at 7:28 PM  

Cat Stevens said

- If you want to sing out, sing out, and if you want to be free, be free, cause there's a million ways to be, you know that there are. -

watashi

My Photo
Name: Monang Setyawan
Location: Jakarta, Indonesia

I'm nothing

likes...

anime, games, Java, watching movies, operating illegal software and music downloads, playing the guitar, reading, football, cats

dislikes...

pineapples, snakes, Bush, Bill Gates, hypocrites

valuable primates

MartinFowler JamesGosling RickardOberg GradyBooch JasonHunter SteveJobs CedricBeust BruceTate HaniSulaiman DionAlmaer BruceEckel CarlosWhoever CameronPurdy GrahamGlass BillBurke GavinKing MarcFleury RichardStallman JamesStrachan ErikHatcher CraigMcClanahan MonsonHaefel GuidoVanRossum JimWaldo Joel Spolsky JackShirazi EricRaymond HeinzKabutz

archives

10/2004
11/2004
01/2005
02/2005
03/2005
04/2005
07/2005
09/2005
11/2005
12/2005
01/2006
02/2006
01/2007
09/2007
10/2007
12/2007

other people

Mr. Good Indonesian
We Hate Indonesia
Zul van Delft

donation provided by

Java-Tips

links

My Wiki
TSS
/.

behind the scene

I like grey because it reminds me of the colour of my brain. My brain conjures up funny or useless thoughts to be ranted in this blog/journal.

Let them speak



This horrible page has been visited for times

theWrittenOne
-Yet Another Useless Blog- Random thought, Java, and anything