Created
July 16, 2014 05:57
-
-
Save adohe-zz/2e67bff12f34ae2f9ba9 to your computer and use it in GitHub Desktop.
Java reflect experience
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.westudio.java; | |
| import java.lang.reflect.InvocationTargetException; | |
| import java.lang.reflect.Modifier; | |
| /** | |
| * Reflect experience | |
| */ | |
| class ReflectClass { | |
| public Runnable runnable = new Runnable() { | |
| @Override | |
| public void run() { | |
| System.out.println("Anonymous inner class"); | |
| } | |
| }; | |
| private class Inner1 { | |
| public Inner1() { | |
| System.out.println("Private inner class"); | |
| } | |
| } | |
| class Inner2 { | |
| public Inner2() { | |
| System.out.println("Default inner class"); | |
| } | |
| } | |
| public class Inner3 { | |
| public Inner3() { | |
| System.out.println("Public inner class"); | |
| } | |
| } | |
| public static class Inner4 { | |
| public Inner4() { | |
| System.out.println("Public static inner class"); | |
| } | |
| } | |
| } | |
| public class Reflect { | |
| public static void main(String[] args) { | |
| ReflectClass reflectClass = new ReflectClass(); | |
| try { | |
| reflectClass(reflectClass); | |
| } catch (Exception e) {/**/} | |
| } | |
| private static void reflectClass(ReflectClass rc) throws NoSuchMethodException, | |
| IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException { | |
| Class clazz = rc.getClass(); | |
| Class[] classes = clazz.getDeclaredClasses(); | |
| for (Class cls : classes) { | |
| int i = cls.getModifiers(); | |
| String modify = Modifier.toString(i); | |
| System.out.println("Mofifier: " + modify); | |
| if (modify.contains("static")) { | |
| cls.getConstructor().newInstance(); | |
| } else { | |
| cls.getConstructor(rc.getClass()).newInstance(rc); | |
| } | |
| } | |
| // Special case for anonymous inner class | |
| Runnable runnable = (Runnable)clazz.getField("runnable").get(rc); | |
| runnable.run(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment