Re: Define Type at runtime

Discussion in 'Java' started by Lew, Sep 8, 2011.

  1. Lew

    Lew Guest

    John wrote:
    > If I have a method:
    > public void someMethod(Object o){
    > ...
    > Entity<T> entity;
    > ....
    > }
    >
    > How could I define at runtime the type T if I have an Object?


    You can do an illegal cast with the help of '@SuppressWarnings("unchecked")' and a 'catch ( ClassCastException exc )'.

    You can under certain circumstances use a run-time type token of type 'Class<T>'.

    You can write your method to be type-safe in the first place and avoid the problem.

    Without some context we can't know what you really want. Your question is far too non-specific.

    --
    Lew
    Lew, Sep 8, 2011
    #1
    1. Advertising

  2. Lew

    BGB Guest

    On 9/8/2011 9:32 AM, Lew wrote:
    > John wrote:
    >> If I have a method:
    >> public void someMethod(Object o){
    >> ...
    >> Entity<T> entity;
    >> ....
    >> }
    >>
    >> How could I define at runtime the type T if I have an Object?

    >
    > You can do an illegal cast with the help of '@SuppressWarnings("unchecked")' and a 'catch ( ClassCastException exc )'.
    >
    > You can under certain circumstances use a run-time type token of type 'Class<T>'.
    >
    > You can write your method to be type-safe in the first place and avoid the problem.
    >
    > Without some context we can't know what you really want. Your question is far too non-specific.
    >


    and, probably, not to forget "instanceof".

    eg, rather than, say:
    Object obja;
    try {
    SomeObject objb=(SomeObject)obja;
    ...
    }catch(ClassCastException ex)
    {
    }

    one could be like:
    if(obja instanceof SomeObject)
    {
    SomeObject objb=(SomeObject)obja;
    ...
    }

    which could be more useful if one wants to do the types N-way...

    if(...)
    {
    ...
    }else if(...)
    {
    ...
    }else ...


    or such...
    BGB, Sep 8, 2011
    #2
    1. Advertising

  3. Lew

    Lew Guest

    BGB wrote:
    > Lew wrote:
    >> John wrote:
    >>> If I have a method:
    >>> public void someMethod(Object o){
    >>> ...
    >>> Entity<T> entity;
    >>> ....
    >>> }
    >>>
    >>> How could I define at runtime the type T if I have an Object?

    >>
    >> You can do an illegal cast with the help of '@SuppressWarnings("unchecked")' and a 'catch ( ClassCastException exc )'.
    >>
    >> You can under certain circumstances use a run-time type token of type 'Class<T>'.
    >>
    >> You can write your method to be type-safe in the first place and avoid the problem.
    >>
    >> Without some context we can't know what you really want. Your question is far too non-specific.
    >>

    >
    > and, probably, not to forget "instanceof".


    That's pretty useless in this context.

    > eg, [sic] rather than, say:
    > Object obja;
    > try {
    > SomeObject objb=(SomeObject)obja;
    > ...
    > }catch(ClassCastException ex)
    > {
    > }
    >
    > one could be like:
    > if(obja instanceof SomeObject)
    > {
    > SomeObject objb=(SomeObject)obja;
    > ...
    > }
    >
    > which could be more useful if one wants to do the types N-way...
    >
    > if(...)
    > {
    > ...
    > }else if(...)
    > {
    > ...
    > }else ...
    >
    >
    > or such...


    That's bad advice on several fronts. First of all, the OP was asking about restoring generics information, for which 'instanceof' is not useful, and second, multi-'if' constructs on type are a red flag of bad design. Don't recommend bad design.

    --
    Lew
    Lew, Sep 8, 2011
    #3
  4. Lew

    BGB Guest

    On 9/8/2011 11:25 AM, Lew wrote:
    > BGB wrote:
    >> Lew wrote:
    >>> John wrote:
    >>>> If I have a method:
    >>>> public void someMethod(Object o){
    >>>> ...
    >>>> Entity<T> entity;
    >>>> ....
    >>>> }
    >>>>
    >>>> How could I define at runtime the type T if I have an Object?
    >>>
    >>> You can do an illegal cast with the help of '@SuppressWarnings("unchecked")' and a 'catch ( ClassCastException exc )'.
    >>>
    >>> You can under certain circumstances use a run-time type token of type 'Class<T>'.
    >>>
    >>> You can write your method to be type-safe in the first place and avoid the problem.
    >>>
    >>> Without some context we can't know what you really want. Your question is far too non-specific.
    >>>

    >>
    >> and, probably, not to forget "instanceof".

    >
    > That's pretty useless in this context.
    >
    >> eg, [sic] rather than, say:
    >> Object obja;
    >> try {
    >> SomeObject objb=(SomeObject)obja;
    >> ...
    >> }catch(ClassCastException ex)
    >> {
    >> }
    >>
    >> one could be like:
    >> if(obja instanceof SomeObject)
    >> {
    >> SomeObject objb=(SomeObject)obja;
    >> ...
    >> }
    >>
    >> which could be more useful if one wants to do the types N-way...
    >>
    >> if(...)
    >> {
    >> ...
    >> }else if(...)
    >> {
    >> ...
    >> }else ...
    >>
    >>
    >> or such...

    >
    > That's bad advice on several fronts. First of all, the OP was asking about restoring generics information, for which 'instanceof' is not useful, and second, multi-'if' constructs on type are a red flag of bad design. Don't recommend bad design.
    >


    AFAICT, the OP was asking about dynamic type checking, which is what
    instanceof is for.

    the bigger issue though would be, why the OP was dealing with the case
    in the first case (like, yes, does a common base-class exist besides
    "Object", or is there a common interface, ...), but failing this, nested
    if/else and instanceof does seem like a valid solution (and is probably
    still better than, say, a series of try/catch blocks intermixed with
    return statements).

    try {
    ...
    return;
    }catch(...) { ... }

    try {
    ...
    return;
    }catch(...) { ... }

    ....


    but, whatever works...
    BGB, Sep 8, 2011
    #4
  5. Lew

    Lew Guest

    BGB wrote:
    > Lew wrote:
    >> BGB wrote:
    >>> Lew wrote:
    >>>> John wrote:
    >>>>> If I have a method:
    >>>>> public void someMethod(Object o){
    >>>>> ...
    >>>>> Entity<T> entity;
    >>>>> ....
    >>>>> }
    >>>>>
    >>>>> How could I define at runtime the type T if I have an Object?
    >>>>
    >>>> You can do an illegal cast with the help of '@SuppressWarnings("unchecked")' and a 'catch ( ClassCastException exc )'.
    >>>>
    >>>> You can under certain circumstances use a run-time type token of type 'Class<T>'.
    >>>>
    >>>> You can write your method to be type-safe in the first place and avoidthe problem.
    >>>>
    >>>> Without some context we can't know what you really want. Your question is far too non-specific.
    >>>>
    >>>
    >>> and, probably, not to forget "instanceof".

    >>
    >> That's pretty useless in this context.
    >>
    >>> eg, [sic] rather than, say:
    >>> Object obja;
    >>> try {
    >>> SomeObject objb=(SomeObject)obja;
    >>> ...
    >>> }catch(ClassCastException ex)
    >>> {
    >>> }
    >>>
    >>> one could be like:
    >>> if(obja instanceof SomeObject)
    >>> {
    >>> SomeObject objb=(SomeObject)obja;
    >>> ...
    >>> }
    >>>
    >>> which could be more useful if one wants to do the types N-way...
    >>>
    >>> if(...)
    >>> {
    >>> ...
    >>> }else if(...)
    >>> {
    >>> ...
    >>> }else ...
    >>>
    >>>
    >>> or such...

    >>
    >> That's bad advice on several fronts. First of all, the OP was asking about restoring generics information, for which 'instanceof' is not useful, and second, multi-'if' constructs on type are a red flag of bad design. Don't recommend bad design.
    >>

    >
    > AFAICT, the OP was asking about dynamic type checking, which is what
    > instanceof is for.


    They were asking about the generic type, which most emphatically is *not* what 'instanceof' is for. You even cited the post: "How could I define at runtime the type T if I have an Object?" where "T" was the generic type parameter in the OP's example. 'instanceof' won't help there. In fact, it will not even compile.

    JLS §15.20.2
    "It is a compile-time error if the ReferenceType mentioned after the instanceof operator does not denote a reifiable type (§4.7)."

    > the bigger issue though would be, why the OP was dealing with the case
    > in the first case (like, yes, does a common base-class exist besides
    > "Object", or is there a common interface, ...), but failing this, nested
    > if/else and instanceof does seem like a valid solution (and is probably


    Wrong.

    > still better than, say, a series of try/catch blocks intermixed with
    > return statements).


    Except for that failure-to-compile thing.

    > try {
    > ...
    > return;
    > }catch(...) { ... }
    >
    > try {
    > ...
    > return;
    > }catch(...) { ... }
    >
    > ...
    >
    >
    > but, whatever works...


    By which I assume you at least mean compiles.

    'instanceof Entity<T>' will not compile.

    if-then chains of type comparisons are a major antipattern, a point you gloss over. It means that you aren't using polymorphism and type-safe code. It's a Bad Thing.

    if (x instanceof Foo)
    {
    // do one thing
    }
    else if (x instanceof Bar)
    {
    // do another thing
    }
    else if (x instanceof Baz)
    {
    // OK, this code is far too stupid. Refactor intelligently.
    }
    ....

    You're supposed to have

    Super foo = obtainASubtypeInstance();
    foo.polymorphicMethod();

    --
    Lew
    Lew, Sep 8, 2011
    #5
  6. Lew

    BGB Guest

    On 9/8/2011 2:35 PM, Lew wrote:
    > BGB wrote:
    >> Lew wrote:
    >>> BGB wrote:
    >>>> Lew wrote:
    >>>>> John wrote:
    >>>>>> If I have a method:
    >>>>>> public void someMethod(Object o){
    >>>>>> ...
    >>>>>> Entity<T> entity;
    >>>>>> ....
    >>>>>> }
    >>>>>>
    >>>>>> How could I define at runtime the type T if I have an Object?
    >>>>>
    >>>>> You can do an illegal cast with the help of '@SuppressWarnings("unchecked")' and a 'catch ( ClassCastException exc )'.
    >>>>>
    >>>>> You can under certain circumstances use a run-time type token of type 'Class<T>'.
    >>>>>
    >>>>> You can write your method to be type-safe in the first place and avoid the problem.
    >>>>>
    >>>>> Without some context we can't know what you really want. Your question is far too non-specific.
    >>>>>
    >>>>
    >>>> and, probably, not to forget "instanceof".
    >>>
    >>> That's pretty useless in this context.
    >>>


    <snip>

    >>
    >> but, whatever works...

    >
    > By which I assume you at least mean compiles.
    >
    > 'instanceof Entity<T>' will not compile.
    >


    where did I ever write "instanceof Entity<T>"?...

    the fact that it will not compile, on account of not being valid code,
    is not the issue, because I never wrote that, or suggested that fragment
    as a valid solution...


    > if-then chains of type comparisons are a major antipattern, a point you gloss over. It means that you aren't using polymorphism and type-safe code. It's a Bad Thing.
    >
    > if (x instanceof Foo)
    > {
    > // do one thing
    > }
    > else if (x instanceof Bar)
    > {
    > // do another thing
    > }
    > else if (x instanceof Baz)
    > {
    > // OK, this code is far too stupid. Refactor intelligently.
    > }
    > ...
    >
    > You're supposed to have
    >
    > Super foo = obtainASubtypeInstance();
    > foo.polymorphicMethod();
    >


    but, this only works assuming that some "Super" exists within the class
    heirarchy... what if it does not? what if the original objects in
    question were never designed with this use case in mind? ...

    if it is just a big pile of unrelated objects (with neither a common
    superclass nor a common interface) then instanceof will probably work...


    like, say:
    if(obj instanceof Integer)
    ....
    else if(obj instanceof String)
    ....
    else if(obj instanceof JLabel)
    ....

    but, again, it is a big question of what is being done and why, which
    was not addressed here.


    pattern vs antipattern vs ... isn't really an issue IMO, more just
    scare-tactics and prescriptivism (people don't like something or a way
    of doing something, so they call it an antipattern...).

    the bigger question is when and why someone does something, not that
    they have done it (at least, as far as programming goes).
    BGB, Sep 8, 2011
    #6
  7. Lew

    Lew Guest

    BGB wrote:
    > Lew wrote:
    >> BGB wrote:
    >>> Lew wrote:
    >>>> BGB wrote:
    >>>>>> John wrote:
    >>>>>>> If I have a method:
    >>>>>>> public void someMethod(Object o){
    >>>>>>> ...
    >>>>>>> Entity<T> entity;
    >>>>>>> ....
    >>>>>>> }
    >>>>>>>
    >>>>>>> How could I define at runtime the type T if I have an Object?
    >>>>>>

    ....[snip] ...

    > >>>> and, probably, not to forget "instanceof".
    > >>>
    > >>> That's pretty useless in this context.
    > >>>

    >
    > <snip>
    >
    >>>
    >>> but, whatever works...

    >>
    >> By which I assume you at least mean compiles.
    >>
    >> 'instanceof Entity<T>' will not compile.

    >
    > where did I ever write "instanceof Entity<T>"?...


    You suggested he use 'instanceof' to cast to type 'T' or, depending on whatthe OP meant, 'Entity<T>', since you suggested to use 'instanceof' in the OP's context. Didn't you intend to answer the OP's question, or were you attempting to provide information that didn't pertain to the question at hand?

    If you intended to pertain to the question, then you were advising 'instanceof' to check for a non-reifiable type.

    > the fact that it will not compile, on account of not being valid code,
    > is not the issue, because I never wrote that, or suggested that fragment
    > as a valid solution...
    >
    >> if-then chains of type comparisons are a major antipattern, a point you gloss over. It means that you aren't using polymorphism and type-safe code.. It's a Bad Thing.
    >>
    >> if (x instanceof Foo)
    >> {
    >> // do one thing
    >> }
    >> else if (x instanceof Bar)
    >> {
    >> // do another thing
    >> }
    >> else if (x instanceof Baz)
    >> {
    >> // OK, this code is far too stupid. Refactor intelligently.
    >> }
    >> ...
    >>
    >> You're supposed to have
    >>
    >> Super foo = obtainASubtypeInstance();
    >> foo.polymorphicMethod();
    >>

    >
    > but, this only works assuming that some "Super" exists within the class
    > heirarchy... what if it does not? what if the original objects in
    > question were never designed with this use case in mind? ...


    Then you use overloads instead of overrides.

    Either way, it's probably a case of bad design to have that much 'instanceof' chaining - very much a non-O-O approach.

    > if it is just a big pile of unrelated objects (with neither a common
    > superclass nor a common interface) then instanceof will probably work...


    More likely a refactoring would work better. Yes, it will "work", but it'sbrittle and shows that some analysis was not completed.

    > like, say:
    > if(obj instanceof Integer)
    > ...
    > else if(obj instanceof String)
    > ...
    > else if(obj instanceof JLabel)
    > ...


    The need for such is rare indeed, vanishingly rare. The usual and more maintainable approach is to use overloads. The problem with what you suggest is it pushes compile-time checking into run-time checking.

    > but, again, it is a big question of what is being done and why, which
    > was not addressed here.


    Chance are, though, that what is being done and why is better served by doing things in a more typesafe fashion.

    > pattern vs antipattern vs ... isn't really an issue IMO, more just


    You are correct, that is your opinion.

    > scare-tactics and prescriptivism (people don't like something or a way
    > of doing something, so they call it an antipattern...).


    That's not what I'm doing.

    > the bigger question is when and why someone does something, not that
    > they have done it (at least, as far as programming goes).


    Chance are that the OP's scenario is poorly served by 'instanceof' chains, particularly since they're trying to check on a non-reifiable type and 'instanceof' won't compile anyway.

    You are correct that it depends on the use case, but very few use cases arebest served by the 'instanceof' antipattern. All the ones I've seen in the wild were examples of poor design.

    --
    Lew
    Lew, Sep 9, 2011
    #7
  8. Lew

    BGB Guest

    On 9/8/2011 5:10 PM, Lew wrote:
    > BGB wrote:
    >> Lew wrote:
    >>> BGB wrote:
    >>>> Lew wrote:
    >>>>> BGB wrote:
    >>>>>>> John wrote:
    >>>>>>>> If I have a method:
    >>>>>>>> public void someMethod(Object o){
    >>>>>>>> ...
    >>>>>>>> Entity<T> entity;
    >>>>>>>> ....
    >>>>>>>> }
    >>>>>>>>
    >>>>>>>> How could I define at runtime the type T if I have an Object?
    >>>>>>>

    > ...[snip] ...
    >
    >>>>>> and, probably, not to forget "instanceof".
    >>>>>
    >>>>> That's pretty useless in this context.
    >>>>>

    >>
    >> <snip>
    >>
    >>>>
    >>>> but, whatever works...
    >>>
    >>> By which I assume you at least mean compiles.
    >>>
    >>> 'instanceof Entity<T>' will not compile.

    >>
    >> where did I ever write "instanceof Entity<T>"?...

    >
    > You suggested he use 'instanceof' to cast to type 'T' or, depending on what the OP meant, 'Entity<T>', since you suggested to use 'instanceof' in the OP's context. Didn't you intend to answer the OP's question, or were you attempting to provide information that didn't pertain to the question at hand?
    >


    you misinterpret what I wrote.


    > If you intended to pertain to the question, then you were advising 'instanceof' to check for a non-reifiable type.
    >


    but, not in the way you suggest...

    I was figuring it would have been used in combination with "Entity<?>"
    or "Entity<Object>", so then one can do whatever with the Object.

    granted, I am not entirely sure which "Entity" was in question here (I
    am aware of several things by this name), so it is not entirely clear
    what the intended use of "Entity<T>" was in this context (so, I glossed
    over it partly and assumed it was something that one could "put a T into
    and get a T back out from", under which reasoning, if T was 'Object',
    then it is sufficient to be able to work with an object).


    >> the fact that it will not compile, on account of not being valid code,
    >> is not the issue, because I never wrote that, or suggested that fragment
    >> as a valid solution...
    >>
    >>> if-then chains of type comparisons are a major antipattern, a point you gloss over. It means that you aren't using polymorphism and type-safe code. It's a Bad Thing.
    >>>
    >>> if (x instanceof Foo)
    >>> {
    >>> // do one thing
    >>> }
    >>> else if (x instanceof Bar)
    >>> {
    >>> // do another thing
    >>> }
    >>> else if (x instanceof Baz)
    >>> {
    >>> // OK, this code is far too stupid. Refactor intelligently.
    >>> }
    >>> ...
    >>>
    >>> You're supposed to have
    >>>
    >>> Super foo = obtainASubtypeInstance();
    >>> foo.polymorphicMethod();
    >>>

    >>
    >> but, this only works assuming that some "Super" exists within the class
    >> heirarchy... what if it does not? what if the original objects in
    >> question were never designed with this use case in mind? ...

    >
    > Then you use overloads instead of overrides.
    >


    possibly, unless someone else also declared the classes as 'final'...

    > Either way, it's probably a case of bad design to have that much 'instanceof' chaining - very much a non-O-O approach.
    >


    not saying it is necessarily a good approach, but it is a possible approach.

    one can assume that, if the issue came up, then presumably one already
    has a case where the normal strategies (interfaces, common base classes,
    ....) for whatever reason, wouldn't work.


    yes, base classes and interfaces would probably be a better solution,
    or, if anything, a more efficient one.


    >> if it is just a big pile of unrelated objects (with neither a common
    >> superclass nor a common interface) then instanceof will probably work...

    >
    > More likely a refactoring would work better. Yes, it will "work", but it's brittle and shows that some analysis was not completed.
    >


    typically, but very often programming tasks are very much like trying to
    fit together mismatched parts and figure out where to route all the wiring.

    sometimes, one has to just live with cases where cabling is routed
    through the air vents and drain-pipes, as it were (say, because actually
    "fixing" the problem would require far too much effort, as refactoring
    ones' code may often be more effort than a quick and dirty hack or
    kludge to make it work).


    >> like, say:
    >> if(obj instanceof Integer)
    >> ...
    >> else if(obj instanceof String)
    >> ...
    >> else if(obj instanceof JLabel)
    >> ...

    >
    > The need for such is rare indeed, vanishingly rare. The usual and more maintainable approach is to use overloads. The problem with what you suggest is it pushes compile-time checking into run-time checking.
    >


    fair enough, but I have seen cases like this a few times (and probably
    Sun figured it was a fairly common use-case, after all, they included a
    nice operator for it).

    Microsoft probably thought this use case was even more important, as
    they added an even shorter operator name in C# ('is'), as well as a few
    related operators.


    if it were, in fact, so strange and rare, it is likely that instead one
    would have to do something far more awkward, like, say:
    "obj.getClass().isInstance(Integer.class)" or something...


    so, it seems likely that the language designers figured this use-case
    was likely common and useful enough to add things like a operator for
    it, a dedicated bytecode instruction, ...


    >> but, again, it is a big question of what is being done and why, which
    >> was not addressed here.

    >
    > Chance are, though, that what is being done and why is better served by doing things in a more typesafe fashion.
    >


    possibly, but nothing was said.


    >> pattern vs antipattern vs ... isn't really an issue IMO, more just

    >
    > You are correct, that is your opinion.
    >
    >> scare-tactics and prescriptivism (people don't like something or a way
    >> of doing something, so they call it an antipattern...).

    >
    > That's not what I'm doing.
    >


    whoever probably originally decided to classify it as an antipattern is
    likely to have been doing this.

    like, being all prescriptive over matters of style and similar.


    it is like all of those people who say one can't use a
    knife/fork/screwdriver/... to stir ones' drink, when really anything one
    has in-hand will work, and if it saves having to fetch a spoon or
    whatever, and avoids creating more dishes, presumably all-the-better...

    then, one can be contrary and put the stupid spoon on the end of an
    electric screwdriver or power-drill and stir ones' drink this way...
    (being like "yeah, I am so totally stirring this drink with a spoon...").

    but, then again, I guess there are some things I am fussy about, like
    morals and similar, and I guess on some level, I have a hard time with
    how so many people seem to disregard good morals (like, being all
    promiscuous, being selfish jerks, ...). but, ultimately, they only have
    themselves to blame, so it really isn't worth putting up a big fuss over it.

    but, OTOH, code is code, any why should anyone really care?...
    presumably, if it works, it works.


    >> the bigger question is when and why someone does something, not that
    >> they have done it (at least, as far as programming goes).

    >
    > Chance are that the OP's scenario is poorly served by 'instanceof' chains, particularly since they're trying to check on a non-reifiable type and 'instanceof' won't compile anyway.
    >
    > You are correct that it depends on the use case, but very few use cases are best served by the 'instanceof' antipattern. All the ones I've seen in the wild were examples of poor design.
    >


    who knows, I guess a big mystery is just what the OP was wanting to do
    exactly anyways...


    most use cases I can think of are in trying to do things like implement
    dynamically-typed numeric towers and similar.
    BGB, Sep 9, 2011
    #8
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. theotyflos
    Replies:
    3
    Views:
    455
    Thomas Matthews
    Feb 19, 2004
  2. robin liu
    Replies:
    3
    Views:
    813
    Robin Liu
    Apr 21, 2006
  3. Yevgen Muntyan

    #define ALLOCIT(Type) ((Type*) malloc (sizeof (Type)))

    Yevgen Muntyan, Feb 9, 2007, in forum: C Programming
    Replies:
    10
    Views:
    883
    Yevgen Muntyan
    Feb 13, 2007
  4. Mayeul

    Re: Define Type at runtime

    Mayeul, Sep 7, 2011, in forum: Java
    Replies:
    2
    Views:
    282
    Robert Klemme
    Sep 9, 2011
  5. Brian Takita

    #define _ and #define __

    Brian Takita, Jan 23, 2006, in forum: Ruby
    Replies:
    0
    Views:
    447
    Brian Takita
    Jan 23, 2006
Loading...

Share This Page