反射的应用

反射:根据类的描述,产生类的对象,调用对象的方法。

实例:

package com.xaccp.wm;

//定义类Reflect

public class Reflect {

static{
  System.out.println("这是静态块!");
}

public Reflect() {
  super();
  System.out.println("这是构造方法!");
}
public Reflect(int i)
{
  System.out.println("这是带参数的构造方法,其参数为为"+i);
}

public String speak(String name,int i)
{
  return name+"说话!说了"+i+"遍。";
}

 
}



//反射的测试类:

package com.xaccp.wm;

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

public class Test {
public static void main(String[] args) {
  String className="com.xaccp.wm.Reflect"; //Reflect类的描述
/*//法一:
try {
//加载类
Class c=Class.forName(className);
//实力化对象
Object obj=c.newInstance();
//得到所有的参数
Class [] classes=new Class[]{String.class,int.class};
//调用speak();
Method method=c.getMethod("speak",classes);
//封装参数
Object[] bs=new Object[]{"tom",3};
Object result= method.invoke(obj, bs);
System.out.println(result);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/

 
  //法二
  try {
   //加载类
   Class c=Class.forName(className);
   //调用带有参数的构造方法
   Constructor con=c.getConstructor(new Class[]{int.class});
   //获得对象
//   Object obj=c.newInstance();
   Object obj=con.newInstance(new Object[]{12});
   Method []method=c.getMethods();
   for (Method ms : method) {
    System.out.println(ms.getName());//得到所有方法
   
    if(ms.getName().equals("speak"))
    {
     Object[] bs=new Object[]{"tom",3};
     Object obs=ms.invoke(obj, bs);
     System.out.println(obs);
    }
   }
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InstantiationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (InvocationTargetException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SecurityException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (NoSuchMethodException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
}

}

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