1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 package vogar.target;
18 
19 import java.io.IOException;
20 import java.util.Arrays;
21 import java.util.Collections;
22 import java.util.Set;
23 
24 class ClassFinder {
25     /**
26      * Returns either a Set with the class represented by classOrPackageName as its only element, if
27      * classOrPackageName represents a class, or a Set containing all of the classes contained
28      * within the package represented by classOrPackageName, if it represents a package.
29      *
30      * Throws an exception if it represents neither a class nor a package with at least one class.
31      */
find(String classOrPackageName)32     public Set<Class<?>> find(String classOrPackageName) {
33         try {
34             // if no exception thrown, classOrPackageName must represent a class
35             return Collections.<Class<?>>singleton(Class.forName(classOrPackageName));
36         } catch (ClassNotFoundException e) {
37         }
38         // classOrPackageName might represent a package
39         try {
40             Package aPackage = new ClassPathScanner().scan(classOrPackageName);
41             Set<Class<?>> classes = aPackage.getTopLevelClassesRecursive();
42             if (classes.isEmpty()) {
43                 throw new IllegalArgumentException("No classes in package: " + classOrPackageName +
44                         "; classpath is " + Arrays.toString(ClassPathScanner.getClassPath()));
45             }
46             return classes;
47         } catch (IOException eIO) {
48             throw new RuntimeException(eIO);
49         }
50     }
51 }
52