老师看看我的回答有需要改进的地方吗以及一个问题

来源:3-4 自由编程

Wonwayshon

2021-01-03 20:37:02

package com.imooc.reflect.project;

public class Goods {
    private int id;                //商品编号
    private String name;            //商品名称
    private double price;        //商品价格
    private String description;    //商品描述

    //无参构造及带参构造
    public Goods(int id, String name, double price, String description) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.description = description;
    }

    public Goods() {
        super();
    }

    //get和set方法
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    //toString()方法
    @Override
    public String toString() {
        return "Goods [id=" + id + ", name=" + name + ", price=" + price + ", description=" + description + "]";
    }

    //无返回值的display()方法,方法内输出信息:商品信息
    public void display() {
        System.out.println("商品编号:"+this.getId()+" 商品名称:"+this.getPrice()+" 商品价格:"+this.getPrice()+" 商品描述:"+this.getDescription());
    }



}
package com.imooc.reflect.project;

import java.lang.reflect.Constructor;

import org.junit.Test;

public class ConstrustorTest {

    //通过Constructor获得无参构造方法,并得到Goods类的对象,然后调用display()方法
    @Test
    public void demo1() throws Exception {
        Class clazz=Class.forName("com.imooc.reflect.project.Goods");
        Constructor cons=clazz.getConstructor();
        Goods goods=(Goods)cons.newInstance();
        goods.display();
    }

    //通过Constructor获得有参构造方法,并得到Goods类的对象,然后输出该对象
    @Test
    public void demo2() throws Exception {
        Class clazz=Class.forName("com.imooc.reflect.project.Goods");
        Constructor cons=clazz.getConstructor(int.class,String.class,double.class,String.class);
        Goods goods=(Goods)cons.newInstance(01,"Lumia950xl",5499.99,"搭载全新的Windows Mobile操作系统的设备");
        System.out.println(goods);
    }
}

老师,在如下这部分代码中是为什么int.class不应该用包装类Integer.class吗,基本数据类型为啥也有.class,基本数据类型的.class表示什么呢,和引用数据类型.class表达的一样吗

clazz.getConstructor(int.class,String.class,double.class,String.class);


写回答

1回答

好帮手慕小尤

2021-01-04

同学你好,1. 测试运行同学代码是正确的,棒棒哒!继续加油!

2. 使用int和Integer都是可以的。但建议实体类中定义属性类型时使用Integer,使用int会有默认值。例如:

    学生实体类中有成绩属性int类型,如果学生成绩是0,无法知道学生是缺考还是考了0分。如果使用Integer类型,缺考就是null,考了0分就是0。

3. .class表达的意思是一样的,int.class就是一个int的字节码类,而Integer.class是Integer的字节码类。同学可以理解为是一种语法,一般在需要指定某个类型时会用到,类型需要使用class来指明,比如:Integer-->Integer.class

祝学习愉快!

0

0 学习 · 8016 问题

查看课程