Reflection.java
1 |
|
2 |
import java.lang.reflect.*; |
3 |
/* Reflection.java - Assignments of OOP2, introspection. |
4 |
Copyright 2015 Maarten Vangeneugden |
5 |
|
6 |
Licensed under the Apache License, Version 2.0 (the "License"); |
7 |
you may not use this file except in compliance with the License. |
8 |
You may obtain a copy of the License at |
9 |
|
10 |
https://www.apache.org/licenses/LICENSE-2.0 |
11 |
|
12 |
Unless required by applicable law or agreed to in writing, software |
13 |
distributed under the License is distributed on an "AS IS" BASIS, |
14 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15 |
See the License for the specific language governing permissions and |
16 |
limitations under the License.*/ |
17 |
/** |
18 |
* MethodPrinter - Class that allows the user to pass a class name via the command line, after which a list of its public members and methods is shown. |
19 |
* @author Maarten Vangeneugden - 1438256 |
20 |
*/ |
21 |
class MethodPrinter { |
22 |
public static void main(String[] args) { |
23 |
System.out.println("Class name?"); |
24 |
Scanner scanner = new Scanner(System.in); |
25 |
String name = scanner.nextLine(); |
26 |
|
27 |
try { |
28 |
Class cls = Class.forName(name); |
29 |
Method methods[] = cls.getDeclaredMethods(); |
30 |
Field fields[] = cls.getDeclaredFields(); |
31 |
|
32 |
System.out.println("Methods:"); |
33 |
for (Method method : methods) { |
34 |
System.out.println(method.toString()); |
35 |
} |
36 |
System.out.println("Fields:"); |
37 |
for (Field field : fields) { |
38 |
System.out.println(field.toString()); |
39 |
} |
40 |
|
41 |
} catch(Exception e){ |
42 |
e.printStackTrace(); |
43 |
} |
44 |
} |
45 |
} |
46 |
|
47 |
/** |
48 |
* MethodExecutor - Allows to execute methods from an arbitrary class via the command line. This only works for classes with empty constructors, static methods or static classes. |
49 |
* @author Maarten Vangeneugden - 1438256 |
50 |
*/ |
51 |
class MethodExecutor { |
52 |
public static void main(String[] args) { |
53 |
System.out.println("What method to invoke?"); |
54 |
Scanner scanner = new scanner(System.in); |
55 |
String method = scanner.nextLine(); |
56 |
|
57 |
} |
58 |
} |
59 |