首页 > 代码库 > java反射小练习

java反射小练习

package com.gmw;

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

public class ReflectTest {
    void test(String name,String word){
        System.out.println(name+"说"+word);
    }
    public ReflectTest(String name) {    }
    
    public ReflectTest() {}
    
    public static void main(String[] args) {
            try {
                Class clazz = Class.forName("com.gmw.ReflectTest");
                Constructor<?> cons = clazz.getConstructor(String.class);
                ReflectTest test = (ReflectTest)cons.newInstance("");
                test.test("babybear", "我们分手吧");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException 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();
            }
    }
}