casting in generics

I have a class with a couple of methods that convert from one generic type to another, but I want to return the original value if both: the argument type and the return type are the same. The best option I could come up with was to cast the argument type and wrap it in a try catch statement, but that seems dirty to me.

public WK wrapKey(K key) {...


public abstract class MyClass<K, V extends Comparable, WK, WV> extends BaseClass<Map<WK, WV>, KeyValueBean<K, V>> {

...
public WK wrapKey(K key) {

    try {
        return (WK) key;
    } catch (Exception e) {
        return null;
    }
}

public WV wrapValue(V value) {

    try {
        return (WV) value;
    } catch (Exception e) {
        return null;
    }
}

I thought the other option could be to specify the class type as an argument in the constructor or a setter method, and then use isAssignableFrom:

public WV wrapValue(V value) {
  if (value.class.isAssignableFrom(this.getWrappedValueClass())){
     return WK(V);
  }
  return null;
}

Is there any other way??

Answer:1

I have this small piece of code for a prototype. I'm trying to have it so that on mousePressed() or on mouseClicked() the colour of the line clicked on will change. I can't for the life of me ...

I have a 2D array of 5 rows and 5 columns, all filled with the value 0. How can I make my program do this: Enter any random combination of row and column like 2-5, without the [] ...

Escribí un programa en Java para imprimir 10 mil mil en un bucle for. para (int i = 0; i <1000000; i ++) {System.out.println (i); } Tomó alrededor de 7,5 segundos. Escribí una clase personalizada en Java que ...

Estoy usando Hibernate y PostgreSql. En hibernación tengo dos clases como: Móvil (id, nombre, número de serie, modelo_no) Modelo (id, descripción, valor) Ahora los valores de la clase Modelo se almacenan en la clase Móvil (...