初识反射
package Demo1;
class Demo1 {
/**
* 反射:动态获取类(字节码文件),并对其成员进行运行
* Persion.class
* 获取class的方式
* 1:使用object提供的Class<?>getClass()方法得到字节码文件
* 需要事前存在对象
* 2:每种数据类型都有有个class属性:通过该属性得到就是字节码文件对象
* 需要这种类型先存在
* 3:只需要提供一个字符串
* 推荐使用第三种
*
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws ClassNotFoundException {
fun1();
fun2();
fun3();
}
//使用class的静态方法
public static void fun3() throws ClassNotFoundException{
Class<?>claz=Class.forName("Demo1.Person");
System.out.println(claz.getName());
}
//方式二:
public static void fun2(){
Class claz=Person.class;
System.out.println(claz);
}
//方式三:
public static void fun1(){
Person ren1=new Person();
Class class1=ren1.getClass();
System.out.println(class1);
}
}
=========================================
package Demo1;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Demo1 {
/**
* 动态得到字节码文件并创建对象
* @throws IllegalAccessException
* @throws InstantiationException
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*
*/
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
createObj();
}
public static void createObj() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException{
//得到字节码文件对象
Class<?>claz=Class.forName("Demo1.Person");//Person.class
//创建对象(创建对象坑定用到构造方法。)--使用空参的构造方法创建对象
Object obj = claz.newInstance();
System.out.println(obj);
//创建对象使用有参的构造方法
Constructor con =claz.getConstructor(String.class,int.class);
Object obj2=con.newInstance("小明",12);
System.out.println(obj2);
}
}
====================================================================================
在配置文件中写好属性,用反射加载出来比较方便
新建了一个config的文件夹,并新建了一个属性文件名字叫:config.properties
usb1=Demo1.KeyBoard
usb2=Demo1.Mouse
package Demo1;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Test {
//笔记本运行
//笔记本适使用键盘
public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
NoteBook book=new NoteBook();
book.run();
/*KeyBoard board=new KeyBoard();*/
Properties pro=new Properties();
FileInputStream inputStream=new FileInputStream("config\\config.properties");
pro.load(inputStream);
for (int i = 1; i < pro.size(); i++) {
String value=pro.getProperty("usb"+i);//因为属性列表起的名字是属性名:usb+i;
Class<?> claz = Class.forName(value);
Usb usb = (Usb) claz.newInstance();
book.useUsb(usb);
}
}
}