Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 787649
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T21:14:14+00:00 2026-05-14T21:14:14+00:00

This method that uses method-level generics, that parses the values from a custom POJO,

  • 0

This method that uses method-level generics, that parses the values from a custom POJO, JXlistOfKeyValuePairs (which is exactly that). The only thing is that both the keys and values in JXlistOfKeyValuePairs are Strings.

This method wants to taken in, in addition to the JXlistOfKeyValuePairs instance, a Class<T> that defines which data type to convert the values to (assume that only Boolean, Integer and Float are possible). It then outputs a HashMap with the specified type for the values in its entries.

This is the code that I have got, and it is obviously broken.

private <T extends Object>  Map<String, T>
    fromListOfKeyValuePairs(JXlistOfKeyValuePairs jxval, Class<T> clasz)
{
    Map<String, T> val = new HashMap<String, T>();
    List<Entry> jxents = jxval.getEntry();
    T value;
    String str;
    for (Entry jxent : jxents)
    {
        str = jxent.getValue();
        value = null;
        if (clasz.isAssignableFrom(Boolean.class))
        {
            value = (T)(Boolean.parseBoolean(str));
        } else if (clasz.isAssignableFrom(Integer.class))
        {
            value = (T)(Integer.parseInt(str));
        } else if (clasz.isAssignableFrom(Float.class))
        {
            value = (T)(Float.parseFloat(str));
        }
        else {
            logger.warn("Unsupported value type encountered in key-value pairs, continuing anyway: " +
                clasz.getName());
        }
        val.put(jxent.getKey(), value);
    }
    return val;
}

This is the bit that I want to solve:

if (clasz.isAssignableFrom(Boolean.class))
{
    value = (T)(Boolean.parseBoolean(str));
} else if (clasz.isAssignableFrom(Integer.class))
{
    value = (T)(Integer.parseInt(str));
}

I get: Inconvertible types required: T found: Boolean

Also, if possible, I would like to be able to do this with more elegant code, avoiding Class#isAssignableFrom.

Any suggestions?


Sample method invocation:

Map<String, Boolean> foo = fromListOfKeyValuePairs(bar, Boolean.class);

Solved, thanks to both @Chris Dolan and @polygenelubricants. The cause was the typecast was getting confused when combine with the autoboxing of the primitive. Compiler warnings are avoided because the method parameter clasz is of the type Class<T>, instead of just Class or Class<?>, so invoking the cast method was typesafe.

Impl. soln.:

private <T extends Object> Map<String, T> fromListOfKeyValuePairs(
    JXlistOfKeyValuePairs jxval, Class<T> clasz)
{
    Map<String, T> val = new HashMap<String, T>();
    List<Entry> jxents = jxval.getEntry();
    T value;
    String str;
    for (Entry jxent : jxents)
    {
        str = jxent.getValue();
        value = null;
        if (clasz.isAssignableFrom(Boolean.class))
        {
            value = clasz.cast(Boolean.parseBoolean(str));
        }
        else if (clasz.isAssignableFrom(Integer.class))
        {
            value = clasz.cast(Integer.valueOf(Integer.parseInt(str)));
        }
        else if (clasz.isAssignableFrom(Float.class))
        {
            value = clasz.cast((Object)Float.parseFloat(str));
        }
        else
        {
            logger.warn("Unsupporteded value type encountered in key-value pairs, continuing anyway: " +
                clasz.getName());
        }
        val.put(jxent.getKey(), value);
    }
    return val;
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T21:14:14+00:00Added an answer on May 14, 2026 at 9:14 pm

    You can use the Class<T>.cast method instead of doing your own unchecked (T) cast.

        if (clasz.isAssignableFrom(Boolean.class)) {
            value = clasz.cast(Boolean.parseBoolean(str));
        } else if (clasz.isAssignableFrom(Integer.class)) {
            value = clasz.cast(Integer.parseInteger(str));
        } else if (clasz.isAssignableFrom(Float.class)) {
            value = clasz.cast(Float.parseFloat(str));
        }
    

    No compiler warning.


    As for why the original code doesn’t compile, it’s because you’re trying to cast a primitive directly to an unknown reference type. Casting directly from primitive to a reference type only works in very specific cases, and in all those cases, the type must be known at compile time.

        Object o;
    
        o = (Integer) 42; // works! Boxing conversion!
        o = (Number) 42;  // works! Autoboxing then widening reference conversion!
        o = (Object) 42;  // works! Autoboxing then widening reference conversion!
        o = 42; // YES! This also compiles!!!
    
        o = (String) ((Object) 42); // compiles fine!
        // will throw ClassCastException at run-time
    
        o = (String) 42; // DOESN'T COMPILE!!!
    

    The last line is analogous to your cast from a primitive directly to an unknown parameterized type T (i.e. (T) Integer.parseInt(s)), which is why it doesn’t compile. It’s true that you’re trying to write the code such that T would be the proper type, but there’s no way of confirming that at compile-time, since T can be any type in general.

    The previous to last line gets around the compile-time error by indirectly casting the primitive to String, after it had already been converted to an Object reference type. That’s why it compiles, although of course it will throw a ClassCastException at run-time.

    Here’s a parameterized type generic example: it’s a bit silly, but reillustrates the problem with casting primitives directly to an unknown reference type:

    <T> T f() {
        //return (T) 42; // DOESN'T COMPILE!!!
        return (T) (Integer) 42; // compiles with warning about unchecked cast
    }
    

    References

    • Java language guide/Autoboxing
    • JLS 5.1.7 Boxing conversion
    • JLS 5.1.8 Unboxing conversion
    • JLS 5.1.5 Widening reference conversion
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 385k
  • Answers 385k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I think XSLT is by far the easiest and best… May 14, 2026 at 11:37 pm
  • Editorial Team
    Editorial Team added an answer You are looking for cformsII. This plugin will allow you… May 14, 2026 at 11:37 pm
  • Editorial Team
    Editorial Team added an answer Take a look at the thread.join() method. Basically it will… May 14, 2026 at 11:37 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.