001/*
002 * Copyright 2002-2020 the original author or authors.
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 *      https://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
017package org.springframework.core;
018
019import java.lang.annotation.Annotation;
020
021import org.springframework.lang.Nullable;
022import org.springframework.util.ClassUtils;
023
024/**
025 * A common delegate for detecting Kotlin's presence and for identifying Kotlin types.
026 *
027 * @author Juergen Hoeller
028 * @author Sebastien Deleuze
029 * @since 5.0
030 */
031@SuppressWarnings("unchecked")
032public abstract class KotlinDetector {
033
034        @Nullable
035        private static final Class<? extends Annotation> kotlinMetadata;
036
037        private static final boolean kotlinReflectPresent;
038
039        static {
040                Class<?> metadata;
041                ClassLoader classLoader = KotlinDetector.class.getClassLoader();
042                try {
043                        metadata = ClassUtils.forName("kotlin.Metadata", classLoader);
044                }
045                catch (ClassNotFoundException ex) {
046                        // Kotlin API not available - no Kotlin support
047                        metadata = null;
048                }
049                kotlinMetadata = (Class<? extends Annotation>) metadata;
050                kotlinReflectPresent = ClassUtils.isPresent("kotlin.reflect.full.KClasses", classLoader);
051        }
052
053
054        /**
055         * Determine whether Kotlin is present in general.
056         */
057        public static boolean isKotlinPresent() {
058                return (kotlinMetadata != null);
059        }
060
061        /**
062         * Determine whether Kotlin reflection is present.
063         * @since 5.1
064         */
065        public static boolean isKotlinReflectPresent() {
066                return kotlinReflectPresent;
067        }
068
069        /**
070         * Determine whether the given {@code Class} is a Kotlin type
071         * (with Kotlin metadata present on it).
072         */
073        public static boolean isKotlinType(Class<?> clazz) {
074                return (kotlinMetadata != null && clazz.getDeclaredAnnotation(kotlinMetadata) != null);
075        }
076
077}