Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;

import java.util.List;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Main {
    @SuppressWarnings("unchecked")
    private static final Class<URL>[] parameters = new Class[] { URL.class };

    private static List<String> extractClassNames(String path) throws IOException, NoSuchMethodException,
            SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        addToClassPath(path);
        List<String> classNames = new ArrayList<String>();
        ZipInputStream zipStream = new ZipInputStream(new FileInputStream(path));
        try {
            for (ZipEntry entry = zipStream.getNextEntry(); entry != null; entry = zipStream.getNextEntry()) {
                if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
                    String className = entry.getName().replace('/', '.');
                    classNames.add(className.substring(0, className.length() - ".class".length()));
                }
            }
            return classNames;
        } finally {
            zipStream.close();
        }
    }

    private static void addToClassPath(String path) throws IOException, NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        File file = new File(path);
        if (file.exists()) {
            addtoClassLoader(file.toURI().toURL());
        } else {
            throw new IOException("File Not Found");
        }
    }

    private static void addtoClassLoader(URL url) throws IOException, NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Class<URLClassLoader> sysclass = URLClassLoader.class;
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysloader, new Object[] { url });
    }
}