1、谈谈反射
反射概念:Java 反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。
2、Java练习反射demo
Animal.java
package pang.three;
public class Animal {
private String name;
private Integer age;
public void animalSay(String said) {
System.out.println("name:" + name + ", age:" + age + ", say:" + said);
}
private String greet(String people) {
return "Hello, " + people;
}
}
Reflect.java
package pang.three;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Reflect {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class animalClass = Class.forName("pang.three.Animal");
Animal animal = (Animal) animalClass.newInstance();
// 获取类的三种方法
// System.out.println(animalClass);
// System.out.println(Animal.class);
// System.out.println(animal.getClass());
System.out.println(animalClass.getName());
Method animalGreet = animalClass.getDeclaredMethod("greet", String.class);
animalGreet.setAccessible(true);
Object greetStr = animalGreet.invoke(animal, "SmallPang");
System.out.println("greetStr:" + greetStr);
Method animalSay = animalClass.getMethod("animalSay", String.class);
animalSay.invoke(animal, "叽叽叽");
Field name = animalClass.getDeclaredField("name");
name.setAccessible(true);
name.set(animal, "chicken");
Field age = animalClass.getDeclaredField("age");
age.setAccessible(true);
age.set(animal, 22);
animalSay.invoke(animal, "叽叽叽");
}
}
其中获取的类的三种方法:(面试常常也会考到)
1) Class.forName(类的完整路径)
2) 类.class
3) 类对象.getClass()