Java -- 反射机制

实例化对象的两种形式:

1)通过关键字new

2)通过反射机制完成

package test;

//Book类
class Book {
    private String title;
    private double  price;
    public void setPric(double price) {
        this.price = price;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Override
    public String toString() {
        return "图书名称:"+ title + " 价格:" + price;
    }
}

public class TestReflection {
    public static void main(String[] args) throws Exception {
        Class<?> cls = Class.forName("test.Book"); //包名.类名
        Book book = (Book) cls.newInstance();
        book.setTitle("Java");
        book.setPric(10.01);
        System.out.println(book.toString()); //图书名称:Java 价格:10.01
    }
}

 Q:如果类中没有提供无参构造方法,只提供了有参构造方法,则必须明确调用指定的构造方法才可以通过反射实例化对象

package test;

import java.lang.reflect.Constructor;

//Book类
class Book {
    private String title;
    private double  price;
    public Book(String title,double price){
        this.price = price;
        this.title = title;
    }
    
    
    @Override
    public String toString() {
        return "图书名称:"+ title + " 价格:" + price;
    }
}

public class TestReflection {
    public static void main(String[] args) throws Exception {
        Class<?> cls = Class.forName("test.Book");
        Constructor<?> cons = cls.getConstructor(String.class,double.class);
        Book book = (Book) cons.newInstance("Java",10.01);
        System.out.println(book.toString());                //图书名称:Java 价格:10.01
    }
}

 

posted @ 2018-07-30 17:18  wuyueping  阅读(76)  评论(0编辑  收藏  举报