空指针异常?请老师帮忙,代码如下:

来源:3-10 自由编程

慕粉1465475474

2020-06-23 19:08:12

package com.imooc.reflect.excercise34;


public class Address {


private int no;

private String name;

private String address;

private String tel;

public Address() {

super();

}


public Address(int no, String name, String address, String tel) {

super();

this.no = no;

this.name = name;

this.address = address;

this.tel = tel;

}


public int getNo() {

return no;

}


public void setNo(int no) {

this.no = no;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getAddress() {

return address;

}


public void setAddress(String address) {

this.address = address;

}


public String getTel() {

return tel;

}


public void setTel(String tel) {

this.tel = tel;

}


public void display(){

System.out.println("这是一个地址。。。");

}

private void info(){

System.out.println("我是私有方法...");

}

private void equalsAddress(String name){

if(this.address.equals(name)) {

System.out.println("相同");

}else {

System.out.println("不同");

}

}

@Override

public String toString() {

return "Address [no=" + no + ", name=" + name + ", address=" + address + ", tel=" + tel + "]";

}

}





package com.imooc.reflect.excercise34;


import java.lang.reflect.Method;


import org.junit.Test;


public class AddressTest {


@Test

//通过Method调用公有的display方法

public void demo1() throws Exception {

Class class1 = Class.forName("com.imooc.reflect.excercise34.Address");

//实例化

Address address  =  (Address) class1.newInstance();

//获得私有方法

Method method = class1.getDeclaredMethod("display");

//执行方法

method.invoke(address);

}

@Test

//通过Method调用私有的info方法

public void demo2() throws Exception {

Class class1 = Class.forName("com.imooc.reflect.excercise34.Address");

//实例化

Address addr = (Address) class1.newInstance();

//获得私有方法

Method method = class1.getDeclaredMethod("info", null);

//设置私有属性的访问权限

method.setAccessible(true);

method.invoke(addr);

}

@Test

//通过Method调用equalsAddress方法

public void demo3() throws Exception {

Class class1 = Class.forName("com.imooc.reflect.excercise34.Address");

//实例化

Address add = (Address) class1.newInstance();

//获得私有方法

Method method = class1.getDeclaredMethod("equalsAddress", String.class);

//设置私有属性的访问权限

method.setAccessible(true);

method.invoke(add, "Beijing");

}

}



写回答

1回答

好帮手慕珊

2020-06-24

同学,你好!运行代码提示空指针异常出现在Address.java的122行

http://img.mukewang.com/climg/5ef2adb909b284b107860086.jpg

检查发现是如下代码发生异常,这里考虑address是null,调用方法引起的空指针异常。通过检查代码发现address没有被赋值,使用的是默认值null,所以导致了空指针异常

http://img.mukewang.com/climg/5ef2adf50967d03810220454.jpg

修改建议:在demo3方法中为address赋值

http://img.mukewang.com/climg/5ef2af580985bd2a05460298.jpg

或者可以通过如下反射代码为属性address赋值

Field f=class1.getDeclaredField("address");
f.setAccessible(true);//因为是私有属性,所以需要进行设置后才能赋值
f.set(add, "Beijing");

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


0

0 学习 · 8016 问题

查看课程

相似问题