001/*
002 * Copyright 2002-2014 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.type.filter;
018
019import org.springframework.util.ClassUtils;
020
021/**
022 * A simple filter which matches classes that are assignable to a given type.
023 *
024 * @author Rod Johnson
025 * @author Mark Fisher
026 * @author Ramnivas Laddad
027 * @since 2.5
028 */
029public class AssignableTypeFilter extends AbstractTypeHierarchyTraversingFilter {
030
031        private final Class<?> targetType;
032
033
034        /**
035         * Create a new AssignableTypeFilter for the given type.
036         * @param targetType the type to match
037         */
038        public AssignableTypeFilter(Class<?> targetType) {
039                super(true, true);
040                this.targetType = targetType;
041        }
042
043
044        @Override
045        protected boolean matchClassName(String className) {
046                return this.targetType.getName().equals(className);
047        }
048
049        @Override
050        protected Boolean matchSuperClass(String superClassName) {
051                return matchTargetType(superClassName);
052        }
053
054        @Override
055        protected Boolean matchInterface(String interfaceName) {
056                return matchTargetType(interfaceName);
057        }
058
059        protected Boolean matchTargetType(String typeName) {
060                if (this.targetType.getName().equals(typeName)) {
061                        return true;
062                }
063                else if (Object.class.getName().equals(typeName)) {
064                        return false;
065                }
066                else if (typeName.startsWith("java")) {
067                        try {
068                                Class<?> clazz = ClassUtils.forName(typeName, getClass().getClassLoader());
069                                return this.targetType.isAssignableFrom(clazz);
070                        }
071                        catch (Throwable ex) {
072                                // Class not regularly loadable - can't determine a match that way.
073                        }
074                }
075                return null;
076        }
077
078}