2 * Copyright 2003-2005 Dave Griffith
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.
16 package com.siyeh.ig.psiutils;
18 import com.intellij.psi.*;
19 import org.jetbrains.annotations.NotNull;
21 public class SingletonUtil {
22 private SingletonUtil() {
26 public static boolean isSingleton(@NotNull PsiClass aClass) {
27 if (aClass.isInterface() || aClass.isEnum() || aClass.isAnnotationType()) {
30 if(aClass instanceof PsiTypeParameter ||
31 aClass instanceof PsiAnonymousClass){
34 if (!hasConstructor(aClass)) {
37 if (hasVisibleConstructor(aClass)) {
40 return containsOneStaticSelfInstance(aClass);
43 private static boolean containsOneStaticSelfInstance(PsiClass aClass) {
44 final PsiField[] fields = aClass.getFields();
45 int numSelfInstances = 0;
46 for(final PsiField field : fields){
47 final String className = aClass.getQualifiedName();
48 if(field.hasModifierProperty(PsiModifier.STATIC)){
49 final PsiType type = field.getType();
50 final String fieldTypeName = type.getCanonicalText();
51 if(fieldTypeName.equals(className)){
56 return numSelfInstances == 1;
59 private static boolean hasConstructor(PsiClass aClass) {
60 return aClass.getConstructors().length>0;
63 private static boolean hasVisibleConstructor(PsiClass aClass) {
64 final PsiMethod[] methods = aClass.getConstructors();
65 for(final PsiMethod method : methods){
66 if(method.hasModifierProperty(PsiModifier.PUBLIC)){
69 if(!method.hasModifierProperty(PsiModifier.PRIVATE) &&
70 !method.hasModifierProperty(PsiModifier.PROTECTED)){