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 6331583
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T18:05:51+00:00 2026-05-24T18:05:51+00:00

I’m trying to come up with a function that lets me pass in any

  • 0

I’m trying to come up with a function that lets me pass in any object and a default value, and if the object cannot be casted to the type of the default value, it should return that default value. If the object is null, it should also return the default value.

It should be used like this:

Integer myVar = ConversionHelper.initialize( "123", 0 ) // should return Integer(123)
Integer myVar = ConversionHelper.initialize( "hello", 0 ) // should return Integer(0)

and so on

I tried with the following code:

public static <T> T initialize(Object o, T def) {
    T ret;

    try {
        ret = (T) o;
    } catch (Exception e) {
        ret = def;
    }

    return ret==null ? def : ret;
}

but it fails with basic conversions, like casting an Integer to a String.

EDIT: took many of the suggestions from the answers, and now I’m looking for a way to do it without the series of if.. elseif… elseif and the try catch block that appears in my answer

  • 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-24T18:05:52+00:00Added an answer on May 24, 2026 at 6:05 pm

    Wildcards are only valid as type parameters, not as types. In this case, as you noticed, plain old Object is just as good.

    Another valid signature would be:

    public static <IN, OUT> OUT initialize(IN o, OUT default) { ... }
    

    But this looks to be unnecessary in your case, since the generic types are unbounded.

    As for your strategy of conversion using casting within a try/catch, I’m not sure about it. Someone else should weigh in on that part.

    EDIT: as you’ve discovered, casting is very limited when it comes to all but the simplest conversions of data. You may need to implement mappings to the appropriate parsing method calls depending on the in and out types.

    EDIT2: as an example of what you’re facing, here is a data conversion method somebody wrote for a project I’m on:

    public static <T> T mapValueString(String valueString, Class<T> targetType) {
    
      if (valueString == null) {
         return null;
      }
      else if(targetType.equals(String.class)) {
         return (T)valueString;
      }
      else if (targetType.equals(Date.class)) {
         return (T)MyDateTime.parseDate(valueString);
      }
      else if (targetType.equals(Timestamp.class)) {
         return (T)MyDateTime.parseTimestamp(valueString);
      }
      else if (targetType.equals(Boolean.class)) {
         String upperVal = valueString.toUpperCase();
         if (upperVal.startsWith("T")) {
            return (T)Boolean.TRUE;
         }
         else if (upperVal.startsWith("F")) {
            return (T)Boolean.FALSE;
         }
         else {
            throw new RuntimeException("Failed to parse value string into Boolean object. String was " + valueString + ".");
         }
      }
      else if (targetType.equals(Integer.class)) {
         Integer i;
         try {
            i = Integer.parseInt(valueString);
         }
         catch (NumberFormatException nfe) {
            throw new RuntimeException("Failed to parse value string into Integer object. String was " + valueString + ".", nfe);
         }
         return (T)i;
      }
      else if (targetType.equals(Long.class)) {
        Long l;
        try {
           l = Long.parseLong(valueString);
        }
        catch (NumberFormatException nfe) {
           throw new RuntimeException("Failed to parse value string into Long object. String was " + valueString + ".", nfe);
        }
        return (T)l;
      }
      else if (targetType.equals(Double.class)) {
         Double d;
         try {
            d = Double.parseDouble(valueString);
         }
         catch (NumberFormatException nfe) {
            throw new RuntimeException("Failed to parse value string into Double object. String was " + valueString + ".", nfe);
         }
         return (T)d;
      }
      else {
         throw new RuntimeException("Unsupported java type " + targetType.getName() + ".");
      }
    }
    

    Note that this is only for mapping String to T, where you want to map T1 to T2. Is there a better way? Maybe. Can SO help you find the right strategy? Of course, but the ball’s in your court to ask the right questions.

    EDIT3: Apache Commons’ beanutils.converters might be of help. I haven’t tried it out though, so I can’t remark on it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I need a function that will clean a strings' special characters. I do NOT
I'm trying to create an if statement in PHP that prevents a single post
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I've got a string that has curly quotes in it. I'd like to replace
Seemingly simple, but I cannot find anything relevant on the web. What is the

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.