类名反射&&方法反射

来源:互联网 发布:php时间月份差 编辑:程序博客网 时间:2024/04/29 00:56

通过反射机制,根据类名的字符串,反射对应的类(Class)


/**    提供公共接口*/public interface Service{    public void method1();}
package com;/**    接口实现方法impl1*/public class ServiceImpl1 implements Service{    public void method1(){        System.out.println("I`am ServiceImpl1");    }}
package com;/**    接口实现方法impl2*/public class ServiceImpl2 implements Service{    public void method1(){        System.out.println("I`am ServiceImpl2");    }}
/*接口实现实现多态*/Class clazz1 = Class.forName(com.ServiceImpl1);Service object1 = (Service)clazz1.newInstance();Class clazz2 = Class.forName(com.ServiceImpl2);Service object2 = (Service)clazz2.newInstance();
/*不带参数的方法*/Method method = clazz.getDeclaredMethod("method1"); /*Object[] arguments = new Object[] {new Integer(37)};Method method = clazz.getDeclaredMethod(methodname,new Object[]{int.class,String.class});method.invoke(object , arguments);*/
0 0
原创粉丝点击