-
(1) 示例
public class Solution { void display() { System.out.println("haha"); } public static void main(String[] args) throws Exception { Class solutionClass = Class.forName("Solution"); Solution solution = (Solution) solutionClass.newInstance(); solution.display(); } }
但是,这种方法被废弃了
原因:
This method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) InvocationTargetException.
所以,现在应该用这种方式
public class Solution { void display() { System.out.println("haha"); } public static void main(String[] args) throws Exception { Class solutionClass = Class.forName("Solution"); Solution solution = (Solution) solutionClass.getDeclaredConstructor().newInstance(); solution.display(); } }
(2) Class本身就是一个类,也可以实例化一个Class对象
获取Class对象的三种方法
1° 示例对象.getClass();
2° 类.class;
3° Class.forName(String className);静态方法
(3) 创建新对象的四种方法
1° new
2° 反射
3° clone()
4° 反序列化
-
Java实现函数指针
(1) 函数指针
目的是实现__回调函数__,将函数的指针作为参数传递给另一个函数。这样,这个函数不是被函数的实现方调用,而是在另一个地方被调用,这样可以动态实现功能(例如到底对两个数进行加减乘除中的哪一种操作,取决于传了哪个函数的指针)
(2) Java实现函数指针的方法 – 利用接口
在接口中声明要调用的方法,不同的实现类分别给出这个方法的不同实现,调用时传进不同的实现类实例
示例
interface PlayerButton { public void buttonPressed(Player player); } class StopButton implements PlayerButton { @Override public void buttonPressed(Player player) { player.stop(); } } class StartButton implements PlayerButton { @Override public void buttonPressed(Player player) { player.start(); } } class Player { public void start() { System.out.println("start"); } public void stop() { System.out.println("stop"); } } class FunctionPointerTest { public static void main(String... args) { Player player = new Player(); pressButton(player, new StopButton()); pressButton(player, new StartButton()); } public static void pressButton(Player player, PlayerButton button) { button.buttonPressed(player); } }
(3) 典型示例:
排序传入自定义的Comparator
public static void sort(List list, Comparator<? super T> c);
chapter04_Java基础知识_4_反射,利用接口实现函数指针
最新推荐文章于 2022-08-03 11:57:33 发布