Java ClassLoader defineClass()方法

java.lang.ClassLoader.defineClass(String name, byte[] b, int off, int len) 将 byte 字节流转换为 java.lang.Class 对象。

1 语法

protected final Class<?> defineClass(String name, byte[] b, int off, int len)

2 参数

name:类型的名称

b:字节数组

off:读取起始位置

len:读取数组的长度

3 返回值

该方法返回Class对象。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java ClassLoader defineClass()方法的例子
 */
import java.io.FileInputStream;
import java.lang.*;

public class DefineClassDemo extends ClassLoader {
    public static void main(String args[]) {
        DefineClassDemo t = new DefineClassDemo();
        t.run(args);
    }
    public void run(String args[]) {
        Class n;
        byte b[] = new byte[10000];
        int len = 0;
        String cdir;
        String cfile;

        /* Class is found here: */
        cdir = System.getProperty("com.yiidian", ".");
        cfile = cdir + java.io.File.separator + "HelloWorld.class";

        try {
            /* Construct byte array with complete class image in it. */
            FileInputStream fis = new FileInputStream(cfile);
            int nbytes;
            do {
                nbytes = fis.read(b, len, b.length-len);
                if ( nbytes > 0 ) {
                    len += nbytes;
                }
            } while ( nbytes > 0 );
        } catch ( Throwable x ) {
            System.err.println("Cannot find " + cfile);
            x.printStackTrace();
        }

        /* Define the class with null for the name */
        n = defineClass(null, b, 0, len);

        /* Try to create an instance of it */
        try {
            n.newInstance();
        } catch ( Throwable x ) {
            x.printStackTrace();
        }
    }
}

 

 

热门文章

优秀文章