Search code examples
javac++genericsintrospection

Simulating C++-typedefs in Java


Can typedef FooBar Bar; and the access to the type FooBar through the expression Foo::Bar in the code

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

be translated to Java?

What would be the Java equivalent for an indirect reference to a type?

The STL and boost are filled with code such as

typedef T              value_type;
typedef T*             iterator;

and I am wondering whether Java supports a similar generic programming idiom. I am still interested in an answer even if the type indirection cannot be done at compile time.

Edit The question (how to do nontrivial generic programming in Java) is not getting any interest from those conversant in Java. I am now adding "C++" as a tag.


Solution

  • The C++ program in the question translates to the following Java code:

    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" );
        }
    }
    

    This is not as efficient as the C++ code. The types are determined in the C++ version during compilation. In the Java version they are determined at run-time.

    A better answer that remedies this issue is most welcome.