本帖最后由 赵许星 于 2013-11-21 21:28 编辑
- //反射
- package com.itheima;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- public class Test8 {
-
- public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
-
- //类的字节码
- //第一种 获取默认构造函数
- System.out.println(Class.forName("com.itheima.Student")+"-----"+Student.class);
- ((Student) Class.forName("com.itheima.Student").newInstance()).printInfo();
-
- //第二种获取指构造函数
- Constructor constructor = Class.forName("com.itheima.Student").getConstructor(String.class,String.class);
- Student student = (Student) constructor.newInstance("zhang","23"); //为何报错!!!!!
- student.printInfo();
- }
- }
- class Student{
- private String name;
- private String age;
-
- Student()
- {
- name="defined";
- age="0";
- }
- Student(String name,String age)
- {
- this.name = name;
- this.age = age;
- }
- void printInfo()
- {
- System.out.println("姓名:"+name+" 年龄:"+age);
- }
- }
- /*
- *
- * 1、类名.class;例如:System.class;
- 2、对象.getClass(),例如:new Stirng(“abc”).getClass();
- 3、Class.forName(“类名”),例如:Class.forName(“java.lang.String”);
- * */
复制代码
大家把代码拷贝一下,运行试试,
Constructor constructor = Class.forName("com.itheima.Student").getConstructor(String.class,String.class); |
|