java 对缺乏潜在类型机制的补偿 :反射

本文介绍了一个使用Java反射机制的示例程序,展示了如何通过反射动态地确定对象的方法并调用它们。具体包括从不同类型的对象中查找并执行'speak'和'sit'方法的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package lu.generics;
import static lu.utils.Print.*;
import java.lang.reflect.Method;
/*
 * 通过反射,CommunicateReflectively.perform()能够动态地确定所需要的方法是否可用并调用他们。
 * 他甚至能够处理Mime只有一个必须的方法这一事实,并能够部分实现其目标。
 * 反射将所有的类型检查都转移到了运行时,因此在许多情况下并不是我们所希望的。*/
class Mime{
	public void walkAgainstTheWind(){}
	public void sit(){print("Pretending to sit");}
	public void pushInvisibleWalls(){}
	public String toString(){return "Mine";}
}
class SmartDog{
	public void speak(){
		print("Woof!");
	}
	public void sit(){print("Sitting");}
	public void reproduce(){}
}
class CommunicateReflectively{
	public static void perform(Object speaker){
		Class<?> spkr=speaker.getClass();
		try{
			try{
				Method speak=spkr.getMethod("speak");
				speak.invoke(speaker);
			}catch(NoSuchMethodException e){
				print(speaker+" cannot speak");
			}
			try{
				Method sit=spkr.getMethod("sit");
				sit.invoke(speaker);
			}catch(NoSuchMethodException e){
				print(speaker+" cannot sit");
			}
		}catch(Exception e){
			throw new RuntimeException(speaker.toString(),e);
		}
	}
}
public class LatentReflection {
   public static void main(String[]args){
	   CommunicateReflectively.perform(new SmartDog());
	   CommunicateReflectively.perform(new Robot());
	   CommunicateReflectively.perform(new Mime());
   }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值