1

可以和通过代码中typedef FooBar Bar;的表达式获取类型FooBarFoo::Bar

#include <typeinfo>
#include <iostream>

class FooBar {};
class FooBat {};

class Foo
{
public:
    typedef FooBar Bar;
    typedef FooBat Bat;
};

int main()
{
    if( typeid(Foo::Bar) == typeid(FooBar) && 
        typeid(Foo::Bat) == typeid(FooBat) )
        std::cout << "All is well." << std::endl;
}

被翻译成Java?

对类型的间接引用的 Java 等价物是什么?

STL 和 boost 中充满了诸如

typedef T              value_type;
typedef T*             iterator;

我想知道Java是否支持类似的通用编程习惯。即使无法在编译时完成类型间接,我仍然对答案感兴趣。

编辑 这个问题(如何在 Java 中进行非平凡的泛型编程)并没有引起那些精通 Java 的人的兴趣。我现在添加“C++”作为标签。

4

2 回答 2

2

您可以将类与以下内容进行比较:

Object a = . . .;
Object b = . . .;
if (a.getClass().equals(b.getClass())) {
    // a and b are instances of the same class
}
if (a.getClass().isAssignableFrom(b.getClass())) {
    // the class of a is a superclass of b's class
}

但是,Java 没有类似的东西typedef允许您使用一种类型名称作为另一种类型的别名。

于 2012-11-09T02:39:30.223 回答
2

问题中的 C++ 程序转换为以下 Java 代码:

public class FooBat {}
public class FooBar {}

public class Foo {
    public static Class get_Bar() { return FooBar.class; }
    public static Class get_Bat() { return FooBat.class; }
}

public class Introspect {
    public static void main(String[] args) {
        if( Foo.get_Bar() == FooBar.class &&
            Foo.get_Bat() == FooBat.class )
            System.out.println( "All is well.\n" );
    }
}

这不如 C++ 代码高效。类型在编译期间在 C++ 版本中确定。在 Java 版本中,它们是在运行时确定的。

一个更好的答案来解决这个问题是最受欢迎的。

于 2012-11-26T21:35:46.680 回答