Java中反射及动态编译

1.先写个Users类,然后通过反射,操作这个类

package tk.javazhangwei.testReflection;

public class Users {
	private int id;
	private int age;
	private String name;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Users(int id, int age, String name) {
		super();
		this.id = id;
		this.age = age;
		this.name = name;
	}
	public Users() {
		// TODO Auto-generated constructor stub
	}
}


2.通过反射来操作构造器,方法等等


package tk.javazhangwei.testReflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/***
 * 通过反射动态的api,操作构造器 方法 属性
 * @author zw
 *
 */
public class Demo02 {
	
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
		String path ="tk.javazhangwei.testReflection.Users";
		try {
			Class clazz = (Class)Class.forName(path);
			Users u = clazz.newInstance();
			
			Constructor  u1= clazz.getDeclaredConstructor(int.class,int.class,String.class);
			Users u2 = u1.newInstance(1001,18,"张伟");
			System.out.println(u2.getName());
			
			
			//通过反射Api,调用普通方法
			Users u3 = clazz.newInstance();
			//u3.setName("老宋");
			Method method = clazz.getDeclaredMethod("setName", String.class);
			method.invoke(u3, "老王");//相当于u3.setName();
			System.out.println(u3.getName());
			
			//通过反射操作属性
			Users u4 = clazz.newInstance();
			Field f = clazz.getDeclaredField("name");
			f.setAccessible(true);//这个属性不需要做安全检查了  直接访问
			f.set(u4, "老宋");//通过反射写属性
			System.out.println(u4.getName());
			System.out.println(f.get(u4));
			
			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

3.Java中动态编译


package tk.javazhangwei.testDynamicCompile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
/***
 * 动态编译java 并且运行
 * @author zw
 *
 */

public class Demo01 {

	public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		
		String msg ="public class msg{public static void main(String[] args){System.out.println(\"nishizhu\");}}";
		File f = new File("d:/mycode/test/msg.java");
		OutputStream os = new FileOutputStream(f);
		byte[] data = msg.getBytes();
		os.write(data, 0, data.length);
		os.flush();
		System.out.println("写入文件成功~");
		os.close();
		
		
		
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		int result = compiler.run(null, null, null, "d:/mycode/test/msg.java");
		System.out.println(result==0?"编译成功":"编译失败 ");
		
		//常规方法
		/*Runtime run =Runtime.getRuntime();
		Process process =run.exec("java -cp d:/mycode/test/ msg");
		InputStream is = process.getInputStream();
		BufferedReader bw = new BufferedReader(new InputStreamReader(is));
		String info = "";
		while((info=bw.readLine())!=null) {
			System.out.println("编译结果"+info);
		}
		is.close();*/
		//
		URL[] urls = new URL[] {new URL("file:/"+"d:/mycode/test/")};
		URLClassLoader loader = new URLClassLoader(urls);
		Class c =loader.loadClass("msg");
		Method m =c.getMethod("main", String[].class);
		m.invoke(null, (Object)new String[] {});
	}

}




你可能感兴趣的:(JavaSE笔记)