java反射

import java.lang.reflect.*;
class ReflectTest 
{
	public static void main(String[] args) throws Exception
	{
		ReflectTest rt = new ReflectTest();
		if(args.length>0)
		{
			String className = args[0];
			Class cl = Class.forName(className);
			Object o = rt.getObject(cl,args);
			System.out.println("对象:"+o);
		}
	}

	//用反射产生对象并返回该对象
	public Object getObject(Class cl,String[] args) throws Exception
	{
		int con_Count = Integer.parseInt(args[1]);
		Object o = null;
		if(con_Count==0)
		{
			o = cl.newInstance();
		}
		else
		{
			Class[] con_Args = new Class[con_Count];
			Object[] obj_Args = new Object[con_Count];
			Object[] oo = null;
			for(int i=0;i<con_Count;i++)
			{
				oo = turn(args[2+i],args[2+i+con_Count]);

				con_Args[i] = (Class)oo[0];
				obj_Args[i] = oo[1];

			}
			Constructor con = cl.getDeclaredConstructor(con_Args);
			o = con.newInstance(obj_Args);
		}
		return o;
	}

	//用反射执行某一方法并返回结果
	public Object invoke(Class cl,Object o,String[] args) throws Exception
	{
		int con_Count = Integer.parseInt(args[1]);
		String methodName = args[2+2*con_Count];		
		int me_Count = Integer.parseInt(args[3+2*con_Count]);
		Class[] me_Args = new Class[me_Count];
		Object[] me_Obj_Args = new Object[me_Count];
		Object[] oo = null;
		for(int i=0;i<me_Count;i++)
		{
			oo = turn(args[4+2*con_Count+i],args[4+2*con_Count+i+me_Count]);

			me_Args[i] = (Class)oo[0];
			me_Obj_Args[i] = oo[1];			
		}

		Method m = cl.getDeclaredMethod(methodName,me_Args);
		Object res = m.invoke(o,me_Obj_Args);
		//System.out.println("方案执行结果:"+res);
		return res;
	}

	public Object[] turn(String cType,String oArg)
	{
		Object[] o = new Object[2];

		if(cType.equals("int"))
		{
			o[0] = int.class;
			o[1] = Integer.parseInt(oArg);
		}
		if(cType.equals("String"))
		{
			o[0] = String.class;
			o[1] = oArg;
		}
		if(cType.equals("float"))
		{
			o[0] = float.class;
			o[1] = Float.parseFloat(oArg);
		}
		if(cType.equals("char"))
		{
			o[0] = char.class;
			o[1] = oArg.charAt(0);
		}
		if(cType.equals("boolean"))
		{
			o[0] = boolean.class;
			o[1] = Boolean.parseBoolean(oArg);
		}
		return o;
	}
}

 

你可能感兴趣的:(java,OO)