一、代码实现
1.接口创建
package work11_2022_12_08;
public interface Car {
void driver();
}
2.实现类创建
a.实现类①
package work11_2022_12_08;
public class Car_1 implements Car{
@Override
public void driver() {
System.out.println("汽车一号正在行驶。。。。。。");
}
}
b.实现类②
package work11_2022_12_08;
public class Car_2 implements Car{
@Override
public void driver() {
System.out.println("汽车二号正在行驶。。。。。。");
}
}
c.实现类③
package work11_2022_12_08;
public class Car_3 implements Car{
@Override
public void driver() {
System.out.println("汽车三号正在行驶。。。。。。");
}
}
3.测试类编写
package work11_2022_12_08;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CarTest {
public static void main(String[] args){
Car car1 = extracted("work11_2022_12_08.Car_1");
car1.driver();
System.out.println("------------------------------------");
Car car2 = extracted("work11_2022_12_08.Car_2");
car2.driver();
System.out.println("------------------------------------");
Car car3 = extracted("work11_2022_12_08.Car_3");
car3.driver();
}
private static Car extracted(String classPath) {
try {
Class forName = Class.forName(classPath);
// Method declaredMethod = forName.getDeclaredMethod("driver");
Car car = (Car) forName.newInstance();
return car;
// declaredMethod.invoke(newInstance);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
return null;
}
}
二、测试