自定义ClassLoader和反射

package reflect;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class TestClassLoader extends ClassLoader
{
    
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException
    {
        InputStream in = null;
        try
        {
            String jarFilePath = "C:/XXXX/omu.jar";
            //String classfile = "com/XXX/ABC.class";
            
            JarFile jarFile = new JarFile(jarFilePath);
            JarEntry entry = jarFile.getJarEntry(name);
            if (entry == null)
            {
                return super.findClass(name);
            }
            in = jarFile.getInputStream(entry); 
            int  size = (int)entry.getSize();
            
            byte[] b = new byte[size];
//            ByteBuffer bytebuffer = ByteBuffer.allocate(size);
            
            int offset = 0;
            while(true)
            {
                
                int length = in.read(b,offset,size-offset);
                offset += length;
                if (offset>=size)
                {
                    break; 
                }
            }
            
            
            return defineClass(name, b, 0, size);
            
        }
        catch (IOException e)
        {
            //throw new ClassNotFoundException(name, e);
            return super.findClass(name);
        }
        finally
        {
            if (in != null)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
     
        
    }    

    public static void main(String[] args) throws ClassNotFoundException
    {
        TestClassLoader loader = new TestClassLoader();
        Class<?> classDef = loader.loadClass("com.upgrade.UpgradeMain"); 
        
        System.out.println(classDef);
    }
   
}

 

 

            Class classDefinition = Class.forName(className);
            Object object = classDefinition.newInstance();
            
            Class[] args = new Class[]{int.class, int.class};
            Method m = classDefinition.getMethod("setSize", args );
            
            m.invoke(object, 5, 6); // 调用这个类的setSize(int , int ) 方法

 

 

你可能感兴趣的:(java,C++,c,C#)