DLIK DLIK - 1 year ago 72
Java Question

Showerthought: Datatype for dataype?

I'm not that experienced with programming, so sorry if this doesn't make any sense. Anyways: Is there a Datatype for datatypes?
This sounds really weird, so here's an example how one could use it:

DataType dt = new DataType("int");
dt i = 3;
double d = 5;
int castedD = (dt) d;


Eventhough I'm pretty sure the compiler(or interpreter?) makes this kind of syntax impossible, it is quite an interesting idea in my opinion.
Does a similar thing already exist? Sorry again if this doesn't make any sense, I was just wondering if this is stupid or a good idea. :)

Answer Source

Nothing like that is possible in Java. You cannot use a value as a type in Java source code:

  • The Java language specification states that type names and variable names are taken from different namespaces. So your example code actually tells the compiler look for a class whose name is dt.

  • If this sort of thing was allowed, Java would no longer be a statically typed programming language.

Now you can do this kind of thing in Java using reflection, but the code is nowhere like as elegant as your (phantasy) code. It is an order of magnitude (or more) slower than conventional Java code, and much more fragile because the compiler can offer you little in the way of error checking.

I can't think of any mainstream programming language (static or dynamically types) that allows variables to be used as types like that. Please comment if you know of one ....

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download