demo类:
反射工具类:ReflectionUtil.java
父类:Animal.java
子类1:Dog.java
子类2:Cat.java
测试启动类:Test.java
测试代码:
反射工具类:ReflectionUtil.java
:
package cn.ckk.reflect;
import java.lang.reflect.Method;
/**
* @author Administrator
*/
public class ReflectionUtil {
/**
* 反射调用指定方法
* @param owner 类的实例
* @param methodName 方法名
* @param argsClass 参数类型
* @param args 参数
* @return
* @throws Exception
*/
public static Object invokeMethod(Object owner, String methodName, Class[] argsClass, Object[] args) throws Exception{
Class ownerClass = owner.getClass();
// 如果调用父类的方法,则父类中的方法必须声明为public
Method method = ownerClass.getMethod(methodName, argsClass);
Object objRtn = method.invoke(owner, args);
return objRtn;
}
}
父类:Animal.java
:
package cn.ckk.reflect;
public class Animal {
private String name;
protected void introduceHimself(String name) throws Exception {
this.name = name;
// Class[] argsClass = new Class[]{String.class};
// Object[] args = new Object[]{name};
Class[] argsClass = new Class[0];
Object[] args = new Object[0];
ReflectionUtil.invokeMethod(this, "eat", argsClass, args);
ReflectionUtil.invokeMethod(this, "eatWhat", argsClass, args);
ReflectionUtil.invokeMethod(this, "makeSound", argsClass, args);
}
public void eat(){
System.out.println("Hi, I'm "+ this.name + ", I'm hungry now, I need something to eat!");
}
public void eatWhat(){
System.out.println("eat something...?");
}
}
子类1:Dog.java
:
package cn.ckk.reflect;
import org.springframework.stereotype.Component;
@Component
public class Dog extends Animal {
@Override
public void eatWhat(){
System.out.println("I'm a dog, I like eating meat!");
}
public void makeSound(){
System.out.println("I'm a dog, so I can bark!");
}
}
子类2:Cat.java
:
package cn.ckk.reflect;
import org.springframework.stereotype.Component;
@Component
public class Cat extends Animal {
@Override
public void eatWhat(){
System.out.println("I'm a cat, I like eating fish!");
}
public void makeSound(){
System.out.println("I'm a cat, so I can meow meow!");
}
}
测试启动类:Test.java
:
package cn.ckk.reflect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class Test implements CommandLineRunner {
@Autowired
private Dog dog;
@Autowired
private Cat cat;
@Override
public void run(String... args) throws Exception {
dog.introduceHimself("汪老大");
cat.introduceHimself("喵老二");
}
}
测试启动类结果:
Hi, I'm 汪老大, I'm hungry now, I need something to eat!
I'm a dog, I like eating meat!
I'm a dog, so I can bark!
Hi, I'm 喵老二, I'm hungry now, I need something to eat!
I'm a cat, I like eating fish!
I'm a cat, so I can meow meow!