运行时编译时类型 [英] compile time type at runtime
问题描述
Java 中有没有办法在运行时获取引用的编译时类型?
Is there any way in Java to get the compile time type of a reference at runtime?
示例:
private void doSomething(final Object o)
{
// do somthing
}
final Number n = 1;
doSomething(n);
final Object o = 1;
doSomething(o);
final Integer i = 1;
doSomething(i);
第一个电话 --> 号码
1st call --> Number
第二次调用 --> 对象
2nd call --> Object
第三次调用 --> 整数
3rd call --> Integer
这是问题的一个非常简化的版本.我想要做的是检测(而不是被告知)关于正在传递的对象的框架元数据.可能发生的情况是,该方法首先使用 Integer 调用,然后使用 Double 调用,两者都声明为 Number.
This is a very simplified version of the problem. What i am trying to do is to detect(instead of being told) inside a framework metadata about objects being passed. What could happen is, that the method gets first called with an Integer and then with a Double, both declared as Number.
推荐答案
我看到的唯一方法是使用重载.但是您需要为继承关系的每个类指定一个覆盖方法以排除子类.
The only way I see is to use overloading. But you would need to specify a overlading method for each class of the inheritance relation to exclude sub classes.
private void doSomething(final Object o)
{
// do something
}
private void doSomething(final Number n)
{
// do something
}
private void doSomething(final Integer i)
{
// do something
}
final Number n = 1;
doSomething(n); // doSomething(final Number) is called.
这篇关于运行时编译时类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!