本帖最后由 地狱天堂 于 2014-8-23 11:29 编辑
反射中创建类的实例. 打印输出,为什么在Person类中定义的toString()方法就会报错??- <p><p>public class Person {
- private String name;
- private int age;
- public Person(){
- System.out.println("Person run");
- }
- public Person(String name,int age){
- this.name=name;
- this.age=age;
- }</p><p>public String toString() {
- return "name:"+name.toString()+",age:"+age;
- }
-
- public void show(String name,int age){
- System.out.println("show run..name="+name+",age="+age);
- }
-
- public static void staticShow(){
- System.out.println("static show run");
- }
- }
- </p></p>
复制代码- <p>
- public class Reflect_GetClassDemo {
- public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
- getClass_3();
- }
- public static void getClass_3() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
- String className="review11Reflect.Person";
- Class clazz=Class.forName(className);
- System.out.println(clazz);
- Object obj=clazz.newInstance();
- System.out.println(obj);
-
- }
-
-
- }
- 报错信息:</p><p>Exception in thread "main" java.lang.NullPointerException
- at review11Reflect.Person.toString(Person.java:15)
- at java.lang.String.valueOf(Unknown Source)
- at java.io.PrintStream.println(Unknown Source)
- at review11Reflect.Reflect_GetClassDemo.getClass_3(Reflect_GetClassDemo.java:28)
- at review11Reflect.Reflect_GetClassDemo.main(Reflect_GetClassDemo.java:20)</p><p> </p>
复制代码 |
|