Type safety: unchecked cast from Object to

Type safety: unchecked cast from Object to

Starting with Java 5.0, the warning “Type safety: unchecked cast from Object to ~.

The “~” is a concrete generic type.

For example, “Map<String,String>”.

An easy workaround for this error is to append an annotation above the method.

@SuppressWarnings("unchecked")

Here is an example

package com.confrage;

import java.util.HashMap;
import java.util.Map;

public class TestMain {
  /**
   * @param args
   */
  @SuppressWarnings("unchecked")
  public static void main(String[] args) {
    Object obj = new Object();
    Map<String, String> map = new HashMap<String, String>();
    map = (Map<String, String>) obj;
  }
}

What is generic type (generics)?

Types such as List<String>やMap<String,String>.

How to handle warnings

Only for one autoCast method Add @SuppressWarnings(“unchecked”) and wrap and code for methods that return an Object class, etc. as follows.

package co.confrage;

import java.util.HashMap;
import java.util.Map;

public class TestMain {
  /**
   * @param args
   */
  public static void main(String[] args) {
    Object obj = new Object();
    Map<String, String> map = new HashMap<String, String>();
    map = autoCast(obj);// Wrap.
  }
  @SuppressWarnings("unchecked")
  public static <T> T autoCast(Object obj) {
    T castObj = (T) obj;
    return castObj;
  }
}

The above is a sample, but methods such as the autoCast method should be written in a common or parent class.

Here is an example of converting an object to a List.

public <T> List<T> castToList(Object target) {
  return objectMapper.convertValue(target, new TypeReference<List<T>>() {});
}

コメント

タイトルとURLをコピーしました