001    /*
002     * Created on Jan 25, 2009
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005     * in compliance with the License. You may obtain a copy of the License at
006     *
007     * http://www.apache.org/licenses/LICENSE-2.0
008     *
009     * Unless required by applicable law or agreed to in writing, software distributed under the License
010     * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011     * or implied. See the License for the specific language governing permissions and limitations under
012     * the License.
013     *
014     * Copyright @2009 the original author or authors.
015     */
016    package org.fest.reflect.innerclass;
017    
018    import static org.fest.util.Strings.concat;
019    
020    import org.fest.reflect.exception.ReflectionError;
021    
022    /**
023     * Understands how to obtain a reference to a static inner class.
024     *
025     * @author Alex Ruiz
026     *
027     * @since 1.1
028     */
029    public class Invoker {
030    
031      static Invoker newInvoker(Class<?> declaringClass, String innerClassName) {
032        if (declaringClass == null) throw new NullPointerException("The declaring class should not be null");
033        return new Invoker(declaringClass, innerClassName);
034      }
035    
036      private final Class<?> declaringClass;
037      private final String innerClassName;
038    
039      private Invoker(Class<?> declaringClass, String innerClassName) {
040        this.declaringClass = declaringClass;
041        this.innerClassName = innerClassName;
042      }
043    
044      /**
045       * Returns a reference to the static inner class with the specified name in the specified declaring class.
046       * @return a reference to the static inner class with the specified name in the specified declaring class.
047       * @throws ReflectionError if the static inner class does not exist (since 1.2).
048       */
049      public Class<?> get() {
050        String namespace = declaringClass.getName();
051        for (Class<?> innerClass : declaringClass.getDeclaredClasses())
052          if (innerClass.getName().equals(expectedInnerClassName(namespace))) return innerClass;
053        throw new ReflectionError(concat(
054            "The static inner class <", innerClassName, "> cannot be found in ", declaringClass.getName()));
055      }
056    
057      private String expectedInnerClassName(String namespace) {
058        return concat(namespace, "$", innerClassName);
059      }
060    }