001 /*
002 * Copyright 2010-2015 JetBrains s.r.o.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package org.jetbrains.kotlin.codegen;
018
019 import org.jetbrains.annotations.NotNull;
020 import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
021 import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor;
022 import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor;
023 import org.jetbrains.kotlin.load.java.sam.SingleAbstractMethodUtils;
024 import org.jetbrains.kotlin.types.JetType;
025
026 public class SamType {
027 public static SamType create(@NotNull JetType originalType) {
028 if (!SingleAbstractMethodUtils.isSamType(originalType)) return null;
029 return new SamType(originalType);
030 }
031
032 private final JetType type;
033
034 private SamType(@NotNull JetType type) {
035 this.type = type;
036 }
037
038 @NotNull
039 public JetType getType() {
040 return type;
041 }
042
043 @NotNull
044 public JavaClassDescriptor getJavaClassDescriptor() {
045 ClassifierDescriptor classifier = type.getConstructor().getDeclarationDescriptor();
046 assert classifier instanceof JavaClassDescriptor : "Sam interface not a Java class: " + classifier;
047 return (JavaClassDescriptor) classifier;
048 }
049
050 @NotNull
051 public JetType getKotlinFunctionType() {
052 //noinspection ConstantConditions
053 return getJavaClassDescriptor().getFunctionTypeForSamInterface();
054 }
055
056 @NotNull
057 public SimpleFunctionDescriptor getAbstractMethod() {
058 return (SimpleFunctionDescriptor) SingleAbstractMethodUtils.getAbstractMembers(type).get(0);
059 }
060
061 @Override
062 public boolean equals(Object o) {
063 return o instanceof SamType && type.equals(((SamType) o).type);
064 }
065
066 @Override
067 public int hashCode() {
068 return type.hashCode();
069 }
070
071 @Override
072 public String toString() {
073 return "SamType(" + type + ")";
074 }
075 }