Java反射入门(1)

​ 一直听说反射很重要,但是之前一直没有用到过。最近在开发过程中,发现之前很多大佬用了反射,当时就感觉非常的高大上。于是乎,趁着端午节有时间,赶紧学习一波~

​ 先举个栗子看看反射是怎么用的吧。

需求:根据配置文件指定的信息,创建Hero对象并调用方法playHero.

​ 我们先创建两个类和一个配置文件:Hero.java 、 ReflectionDemo.java 、Hero.properties

1
2
3
4
5
6
7
public class Hero {
private String hero1 = "鲁班";
//方法
public void playHero(){
System.out.println("本次使用-" + hero1 + "-英雄");
}
}
1
2
3
4
5
6
7
8
9
public class ReflectionDemo {
public static void main(String[] args) {

}
}

​```properties
classpath = com.yang.reflection.Hero
method = playHero

​ 在这之前,我们是这样调用方法的:

1
2
3
4
5
public static void main(String[] args) {
//先new一个对象,然后进行调用
Hero hero = new Hero();
hero.playHero();
}

​ 如果用反射的话,是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Properties properties = new Properties();
properties.load(new FileInputStream("/Users/qixiangyang/Documents/javaCode/leecodePractice/src/hero.properties"));
String classPath = properties.get("classpath").toString();
String methodName = properties.get("method").toString();
System.out.println("classPath = " + classPath);
System.out.println("methodName = " + methodName);

Class cls = Class.forName(classPath);
Object o = cls.newInstance();
Method method = cls.getMethod(methodName);
method.invoke(o);
}

先记住这种用法,具体的原理后续讲解!