Reputation: 10837
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.
Upvotes: 1
Views: 3780
Reputation: 10837
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.
Upvotes: 2
Reputation: 234847
You can compare classes with:
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
}
However, Java does not have anything like typedef
that allows you to use one type name as an alias for another.
Upvotes: 2