Im making a generic method which get an object and string.
it works at first like this..
public static <K, V> V getValue(Pair<K,V> _pair, String k){ ... }
I thought maybe it works as in main class
GrandChildPair<String, Integer> tst = new GrandChildPair<>("dd", 1);
Integer result = Util.getValue(tst,"dd");
But I wanna bound type extends to childPair not Grand one.. To limit this ..access? till ChildPair lines and not woking that in GrandChildPair. so I've tried first in method definition,
public static <K extends ChildPair<K,V>, V extends ChildPair<K,V> V getValue (
but yes It was dumb so I've searched for maybe 3 hours about multiple type parameter extends in java but I couldn't found yet.. I found other single type pram extends examples but I could't find extend a whole generic type (maybe not good at searching..)
Is there any I can do?
public class Util {
///define method
//// //Type parameters //return type// method name ( prams...) {
public static (Pair extends ChildPair) V getValue (Pair<K,V> _pair, String k) {
if (k != _pair.getK()) return null;
else return _pair.getV();
}
}
public class Pair<K, V> {
private K k;
private V v;
Pair(K k, V v) {
this.k = k;
this.v = v;
}
public K getK() {
return k;
}
public V getV() {
return v;
}
}
public class ChildPair<K, V> extends Pair<K, V> {
public ChildPair(K k, V v) {
super(k, v);
}
}
public class GrandChildPair<K, V> extends ChildPair<K, V> {
public GrandChildPair(K k, V v) {
super(k, v);
}
}
public class Main {
public static void main(String[] args) {
Pair<String, Integer> pair = new Pair<>("someone", 35);
Integer age = Util.getValue(pair, "someone");
System.out.println(age);
ChildPair<String, Integer> childPair = new ChildPair<>("gh", 20);
Integer childAge = Util.getValue(childPair, "sss");
System.out.println(childAge);
}
}
ChildPair<K,V>.Pairis a subclass ofChildPair, which is a subclass ofGrandChildPair, and that you want method to require aChildPair, then your method signature should be:public static <K, V> V getValue(ChildPair<K,V> _pair, String k)Pair extends ChildPair, but in your comment you sayChildPair extends Pair, and the syntaxPair < ChildPairis non-standard and hence means nothing to us, so which is it? Don't answer with a comment. Edit the question and clarify it, e.g. by showing declaration such asclass Pair<K, V> extends ChildPair<K, V>.Util.getValue()with aPair, so declare the method with aPairparameter, i.e.public static <K, V> V getValue(Pair<K, V> _pair, String k). SinceChildPairandGrandChildPairare both subclasses ofPair, the method can also be called with either of those. There is no way to prevent it from being called withGrandChildPair, if that was your question. If that wasn't your question, then I have no idea what you question is.