2012-11-09 51 views
1

typedef FooBar Bar;并在代码模拟C++ - 用Java

#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; 
} 

的访问类型FooBar的通过表达Foo::Bar的typedef被翻译成Java?

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

的STL和提升都充满了这样的代码

typedef T    value_type; 
typedef T*    iterator; 

我想知道的Java是否支持类似的泛型编程成语。 即使类型间接不能在编译时完成,我仍然对答案感兴趣。

编辑 这个问题(如何在Java中进行非平凡的泛型编程)没有得到那些熟悉Java的熟悉者的兴趣。我现在添加“C++”作为标签。

+0

也许这会帮助http://stackoverflow.com/questions/1195206/is-there-a-java-equivalent-or-methodology-for-the-typedef-keyword-in-c – lawrencexu

回答

1

在问题中的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版本中,它们是在运行时确定的。

解决此问题的更好的答案是非常受欢迎的。

+0

你想用这个代码来完成什么? –

+0

假设你正在实现一个图类。你希望它被一个顶点和一个边缘参数化,但你不希望只有任何一对类被允许。所以你写了一个充当图形特征的类(如Foo)。条和蝙蝠是通用顶点和边。代替Introspect,我们将有一个(更长的)类使用两个实际的类FooBat和FooBar。 – Calaf

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东西,可以让你使用一种类型的名称作为另一个别名。

+0

方法get_bar()和get_bat()是我希望Java如何促进泛型编程的一个例子。你可以看看Foo的班级并对其进行评论吗? – Calaf