S
Stefan Ram
For teaching purposes, I'd like to know a Java-SE method
that returns an object whose class is only known at runtime
and can be shown to have at least two possibly values by
running a small program.
It would be best if this would be a static method that can
be called without any preparation.
For example, it would be great, if Java SE had an »input« method,
which returned »java.lang.Integer« or »java.lang.String«
depending on the text typed in the console.
Then I could write:
public class Main
{
public static void main
( final java.lang.String[] args )
{
java.lang.System.out.println
( java.lang.System.in.input().getClass() ); }}
Which would print »java.lang.Integer« (when one
enters »123«) or »java.lang.String« (when one enters »abc«).
However, I am not aware of such a method.
The usual approach is to put objects of different classes
into a heterogeneous container, then reading them in again,
and - surprise! - get objects of different classes.
I wonder, if it can get any simpler, without a container,
without preparation.
A near miss is the field »System.in«, which indeed contains an
object of a proper /subtype/ of the field's type. So it is
somewhat polymorphic. You do not know the actual type until
run-time. It is only boring insofar as it is always the same
subtype.
Possibly, somewhere in the huge Java-SE API there is a little
known field or method I could use.
that returns an object whose class is only known at runtime
and can be shown to have at least two possibly values by
running a small program.
It would be best if this would be a static method that can
be called without any preparation.
For example, it would be great, if Java SE had an »input« method,
which returned »java.lang.Integer« or »java.lang.String«
depending on the text typed in the console.
Then I could write:
public class Main
{
public static void main
( final java.lang.String[] args )
{
java.lang.System.out.println
( java.lang.System.in.input().getClass() ); }}
Which would print »java.lang.Integer« (when one
enters »123«) or »java.lang.String« (when one enters »abc«).
However, I am not aware of such a method.
The usual approach is to put objects of different classes
into a heterogeneous container, then reading them in again,
and - surprise! - get objects of different classes.
I wonder, if it can get any simpler, without a container,
without preparation.
A near miss is the field »System.in«, which indeed contains an
object of a proper /subtype/ of the field's type. So it is
somewhat polymorphic. You do not know the actual type until
run-time. It is only boring insofar as it is always the same
subtype.
Possibly, somewhere in the huge Java-SE API there is a little
known field or method I could use.