本帖最后由 天下 于 2013-11-8 23:34 编辑
我也是根据学习的知识,做的练习代码,为什么就出错呢?红色位置报错
我用反射,获取构造方法,调用带参数的构造方法,创建实例对象- package Test;
- class Animal{
- private String name;
- public Animal(){}
- public void dog(){
- System.out.println("小狗小狗汪汪叫------");
- }
- public Animal(String name){
- this.name=name;
-
- }
- public String toString(){
- System.out.println("带参数的构造函数:"+name);
- return "";
- }
- public String toString(String s){
- System.out.println("带参数的构造函数:"+name);
- System.out.println("带参数的方法:"+s);
- return "";
- }
- }
- package Test;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class ConstructorDemo {
- /**
- * @param args
- */
- public static void main(String[] args)throws Exception {
- // TODO Auto-generated method stub
- Class c=Animal.class;
-
- //获取所有的公共的构造方法,并且打印
- Constructor[] con1=c.getConstructors();
- for(int i=0;i<con1.length;i++){
- System.out.println(con1[i].toString());
- }
-
-
- //调用带参数的构造方法进行创建实例对象
- <span style="background-color: rgb(255, 192, 203);"> Constructor con2=c.getConstructor(String.class);
- Animal a1=(Animal)con2.newInstance("阿黄");
- </span>
- Method m=c.getMethod("toString",null);
- m.invoke(a1, args);
-
- Method m1=c.getMethod("toString",new Class[]{String.class});
- m1.invoke(a1, new Object[]{"你好!!!!"});
- /*Constructor con=c.getConstructor(null);
- Method m=c.getMethod("dog", null);
- System.out.println(con.getName());
- Animal a=(Animal)con.newInstance(null);
- m.invoke(a,args);
- */
- }
- }
复制代码 |