简体   繁体   中英

In Java is there an equivalent of the Convert class from C#?

In C# I liked using the Convert class. It made converting from one type to another easy and consistent. I was thinking about writing a similar class in Java, but I don't want to reinvent the wheel. So I googled around to see if such a thing exists and wasn't getting good results. So is anyone aware of something like this either in the standard libs, google guava, or apache commons?

There is no class like this in java.

The accepted practice in java is to just cast primitives to each other. This is an easy and consistent way of converting from one type to another.

float bar = 4.0f;
int foo = (int) bar;

You can create your own Convert class easily

package com.abc;

public class Convert {
  public static int ToInt(Object obj) {
    try{
      return Integer.parseInt(obj.toString());
    }
    catch(Exception ex){
      return 0;
    }
  }
  public static float ToFloat(Object obj) {
    try{
      return Float.parseFloat(obj.toString());
    }
    catch(Exception ex){
      return 0f;
    }
  }

  public static boolean ToBoolean(Object obj){
    try{
      if(obj.getClass() == Boolean.class)
        return (Boolean)obj;

      return Boolean.parseBoolean(obj.toString());
    }
    catch(Exception ex){
      return false;
    }
  }
}

The above class passing following unit test:

package com.abc;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ConvertTest {

  @Test
  public void ConvertToInt() {
    assertEquals(1, Convert.ToInt(1));
    assertEquals(0, Convert.ToInt("Suresh"));
    assertEquals(0, Convert.ToInt(null));
    assertEquals(0, Convert.ToInt(true));
    assertEquals(0, Convert.ToInt(3.3f));
  }

  @SuppressWarnings("deprecation")
  @Test
  public void ConvertToFloat() {
    assertEquals(1f, Convert.ToFloat(1), 0.001f);
    assertEquals(0f, Convert.ToFloat("Suresh"), 0.001f);
    assertEquals(0f, Convert.ToFloat(null), 0.001f);
    assertEquals(0f, Convert.ToFloat(true), 0.001f);
    assertEquals(3.3f, Convert.ToFloat(3.3f), 0.001f);
  }

  @Test
  public void ConvertToBoolean() {
    assertEquals(false, Convert.ToBoolean(1));
    assertEquals(false, Convert.ToBoolean("Suresh"));
    assertEquals(false, Convert.ToBoolean(null));
    assertEquals(true, Convert.ToBoolean(true));
    assertEquals(false, Convert.ToBoolean(false));
    assertEquals(false, Convert.ToBoolean(3.3f));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM