Java -- 反射机制
Posted wuyueping
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
}
}
以上是关于Java -- 反射机制的主要内容,如果未能解决你的问题,请参考以下文章