public static void changeType(final PsiElement element, final PsiType type) {
    try {
      if (element instanceof PsiTypeCastExpression cast) {
        cast.getCastType().replace(JavaPsiFacade.getElementFactory(cast.getProject()).createTypeElement(type));
      }
      else if (element instanceof PsiVariable field) {
        field.normalizeDeclaration();
        field.getTypeElement().replace(JavaPsiFacade.getElementFactory(field.getProject()).createTypeElement(type));
      }
      else if (element instanceof PsiMethod method) {
        method.getReturnTypeElement().replace(JavaPsiFacade.getElementFactory(method.getProject()).createTypeElement(type));
      }
      else if (element instanceof PsiNewExpression newx) {
        final PsiClassType.ClassResolveResult result = resolveType(type);

        final PsiSubstitutor subst = result.getSubstitutor();
        final PsiTypeParameter[] parms = result.getElement().getTypeParameters();

        if (parms.length > 0 && subst.substitute(parms[0]) != null) {
          PsiJavaCodeReferenceElement classReference = newx.getClassOrAnonymousClassReference();
          PsiReferenceParameterList list = classReference.getParameterList();

          if (list == null) {
            return;
          }

          final PsiElementFactory factory = JavaPsiFacade.getElementFactory(newx.getProject());

          PsiTypeElement[] elements = list.getTypeParameterElements();
          for (PsiTypeElement element1 : elements) {
            element1.delete();
          }

          for (PsiTypeParameter parm : parms) {
            PsiType aType = subst.substitute(parm);

            if (aType instanceof PsiWildcardType) {
              aType = ((PsiWildcardType)aType).getBound();
            }

            list
              .add(factory.createTypeElement(aType == null ? PsiType.getJavaLangObject(list.getManager(), list.getResolveScope()) : aType));
          }

          if (PsiDiamondTypeUtil.canCollapseToDiamond(newx, newx, newx.getType())) {
            RemoveRedundantTypeArgumentsUtil.replaceExplicitWithDiamond(list);
          }
        }
      }
      else {
        LOG.error("Unexpected element type " + element.getClass().getName());
      }
    }
    catch (IncorrectOperationException e) {
      LOG.error("Incorrect Operation Exception thrown in CastRole.\n");
    }
  }
public static void changeType(final PsiElement element, final PsiType type)