2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org
.jetbrains
.idea
.devkit
.util
;
19 import com
.intellij
.psi
.*;
20 import org
.jetbrains
.annotations
.NotNull
;
21 import org
.jetbrains
.annotations
.Nullable
;
24 * @author Konstantin Bulenkov
26 public class PsiUtil
{
30 public static boolean isInstanciatable(@NotNull PsiClass cls
) {
31 final PsiModifierList modifiers
= cls
.getModifierList();
35 || modifiers
.hasModifierProperty(PsiModifier
.ABSTRACT
)
36 || !isPublicOrStaticInnerClass(cls
)) {
40 final PsiMethod
[] constructors
= cls
.getConstructors();
42 if (constructors
.length
== 0) return true;
44 for (PsiMethod constructor
: constructors
) {
45 if (constructor
.getParameterList().getParameters().length
== 0
46 && constructor
.hasModifierProperty(PsiModifier
.PUBLIC
)) {
53 public static boolean isPublicOrStaticInnerClass(@NotNull PsiClass cls
) {
54 final PsiModifierList modifiers
= cls
.getModifierList();
55 if (modifiers
== null) return false;
57 return modifiers
.hasModifierProperty(PsiModifier
.PUBLIC
) &&
58 (cls
.getParent() instanceof PsiFile
|| modifiers
.hasModifierProperty(PsiModifier
.STATIC
));
61 public static boolean isOneStatementMethod(@NotNull PsiMethod method
) {
62 final PsiCodeBlock body
= method
.getBody();
64 && body
.getStatements().length
== 1
65 && body
.getStatements()[0] instanceof PsiReturnStatement
;
69 public static String
getReturnedLiteral(PsiMethod method
, PsiClass cls
) {
70 if (isOneStatementMethod(method
)) {
71 final PsiExpression value
= ((PsiReturnStatement
)method
.getBody().getStatements()[0]).getReturnValue();
72 if (value
instanceof PsiLiteralExpression
) {
73 final Object str
= ((PsiLiteralExpression
)value
).getValue();
74 return str
== null ?
null : str
.toString();
75 } else if (value
instanceof PsiMethodCallExpression
) {
76 if (isSimpleClassNameExpression((PsiMethodCallExpression
)value
)) {
84 private static boolean isSimpleClassNameExpression(PsiMethodCallExpression expr
) {
85 String text
= expr
.getText();
86 if (text
== null) return false;
87 text
= text
.replaceAll(" ", "")
90 .replaceAll("\r", "");
91 return "getClass().getSimpleName()".equals(text
) || "this.getClass().getSimpleName()".equals(text
);
95 public static PsiExpression
getReturnedExpression(PsiMethod method
) {
96 if (isOneStatementMethod(method
)) {
97 return ((PsiReturnStatement
)method
.getBody().getStatements()[0]).getReturnValue();