Home > Software design >  How can I get generic type of PsiClassReferenceType
How can I get generic type of PsiClassReferenceType

Time:04-13

public class RestControllerExample {
    
    @GetMapping("/test")
    public Test<String, Integer> req() {
        return null;
    }
    
    static class Test<T, V> {
        
        private T fieldT;

        private V fieldV;

        public T getFieldT() {
            return fieldT;
        }
        
        public void setFieldT(T fieldT) {
            this.fieldT = fieldT;
        }

        public V getFieldV() {
            return fieldV;
        }

        public void setFieldV(V fieldV) {
            this.fieldV = fieldV;
        }
    }
}

PsiClassReferenceType is Test<String, Integer>. How can I know fieldT is String and fieldV is Integer?

class Test<T, V> just a demo, I can't use the getParameters() method to get the type because the order of the fields is not fixed. It is possible that fieldT is declared after fieldV

CodePudding user response:

field.getType().substitute(classReferenceType.resolveGenerics().getSubstitutor()) should do the job.

  1. fieldT.getType() in your example must return T
  2. classReferenceType.resolveGenerics() (returns a pair of class and its substitutor), in your example Test and T -> String, V -> Integer
  3. method substitute would replace T in the type with a String, V with an Integer
  • Related