The refelction of java is mainly from java.lang.Class;
Class has a lot of useful methods,
1 2 3 4 5 6 7 8 9 10 11
//each class, we can get the Constructor
@CallerSensitive public Constructor<?>[] getConstructors() throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), true); } return copyConstructors(privateGetDeclaredConstructors(true)); }
And constructor has the function
1 2 3 4 5
@CallerSensitive @ForceInline// to ensure Reflection.getCallerClass optimization public T newInstance(Object ... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
Example of a class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//Define a class of User, classUser{ publicUser(){ System.out.println("User construct is called"); } }
//Define a className, string variable is the a class whole path(class name) //create a new user instance, String className = "com.mycompany.app.User"; try { Object u = Class.forName(className).getConstructor().newInstance(); //it's like User u = new User(); } catch (Exception e) { System.out.println(e); }
springframework-bean load the xml file, and eventually create instance of class object.
##Use the annotation (no xml) to implement bean in framework
Firstly use @Configuration annotation to represent this class as configuration class,
//Method is Scope, for method only //@Target({ElementType.TYPE, ElementType.METHOD}) //@Retention(RetentionPolicy.RUNTIME) //@Documented
//Class instance is by default the singleton instance, //but we can use Scop annoation to change to mulitple instances //SCOPE_SINGLETON //SCOPE_PROTOTYPE
@Scope(BeanDefinition.SCOPE_SINGLETON) @Bean public User createUser(){ returnnew User(); }
@Bean(initMethod="cleanup") publicvoidclean(){ System.out.println("cleanup is called"); }
@Scope(BeanDefinition.SCOPE_PROTOTYPE) @Bean public Device createDevice(String addr){ Device d = new Device(); d.setDeviceAddr(addr); return d; } }
Define the actual bean class User, use the @Component annotation,
in the main funciton, to get the User instance, we use AnnotationConfigApplicationContext, as we don’t load beans from xml file, we don’t need to use xml class ClassPathXmlApplicationContext,
1 2 3 4
ApplicationContext context = new AnnotationConfigApplicationContext(UserConfiguration.class); User bean1 = context.getBean("createUser",User.class); System.out.println(bean1); bean1.show();