Reflection of Tinking in java trivial knowledge points

Source: Internet
Author: User


25. Create and use your own class loader
Except for the root loader, the JVM is an instance of the ClassLoader subclass. programmers can use the extends ClassLoader subclass and override its method to implement a custom class loader.
Obtain the detailed information of the corresponding Class through the Class Object

Public class ClassTest {private ClassTest () {} public ClassTest (String s) {System. out. println ("constructor with Parameters");} public void info () {System. out. println ("No parameter method");} public void info (String s) {System. out. println ("parameter method, parameter:" + s);} static class Inner {static {System. out. println ("Inner loaded") ;}} public static void main (String [] args) throws Exception {Class
 
  
Clazz = ClassTest. class; Constructor [] costors = clazz. getConstructors (); System. out. println ("all public constructors of classes corresponding to the Class Object"); for (Constructor c: costors) {System. out. println (c);} Constructor [] allcostors = clazz. getDeclaredConstructors (); System. out. println ("All constructors of classes corresponding to the Class Object"); for (Constructor c: allcostors) {System. out. println (c);} Method mtds [] = clazz. getDeclaredMethods (); System. out. println ("all methods of the Class Object corresponding to the Class"); for (Method c: mtds) {System. out. println (c);} Class inClazz = Class. forName ("ClassTest $ Inner"); System. out. print ("external class corresponding to inClazz:" + inClazz. getDeclaringClass ());}}
 

26. Use reflection to generate and operate on objects
The components in the Class object that can be obtained include the Method (represented by the Method object), the Constructor (represented by the Constructor object), and the Field (represented by the field object ), these three classes are defined in java. lang. under the reflect package. The program can use the Method object to execute the corresponding Method, call the corresponding Constructor to create an object, and directly access and modify the attribute value of the object through the Field object.
After each Class is loaded, the system will generate a Class object for the Class and access this Class in JVM through the Class Object. in Java, there are usually three methods to obtain the Class Object:
Class. forName (): Use the static method forName ("XXX") of the Class ")
Person. class: Call the class attribute of a Class to obtain the class object corresponding to the class.
Call the getClass () method of an Object. This method is a method in the java. lang. Object Class. It returns the Class Object corresponding to the Class of the Object.

Routine: import java. io. FileInputStream; import java. util. *; public class ObjectPoolFactory {// defines an object pool, which is preceded by the object name and followed by the actual object private Map
 
  
ObjectPool = new HashMap
  
   
(); // Defines a method for creating an Object. The program can generate a java Object private Object creatObjet (String clazzName) throws ClassNotFoundException based on the class name provided by passing in a String class name, instantiationException, IllegalAccessException {Class
   Clazz = Class. forName (clazzName); // use reflection to create a java class or interface. lang. class Object return clazz. newInstance ();} // This method initializes the object pool based on the specified file. It creates the object public void initPool (String fileName) {FileInputStream FS = null Based on the configuration file; try {FCM = new FileInputStream (fileName); Properties prop = new Properties (); prop. load (FCM); System. out. println ("prop. stringPropertyNames (): "+ prop. stringPropertyNames (); for (String name: prop. stringPropertyNames () {obje CtPool. put (name, creatObjet (prop. getProperty (name) ;}} catch (Exception e) {System. out. println ("read" + fileName + "Exception! ");} Finally {try {if (FS! = Null) {FS. close () ;}} catch (Exception e2) {e2.printStackTrace () ;}}// retrieve the public object getObject (String name) corresponding to the specified name from the Object) {return objectPool. get (name);} public static void main (String [] args) {ObjectPoolFactory ofy = new ObjectPoolFactory (); ofy. initPool ("obj.txt"); System. out. println (ofy. getObject ("a"); System. out. println (ofy. getObject ("c");}/* output prop. stringPropertyNames (): [B, a, c] Mon Apr 28 22:15:50 CST 2014 [] */configuration file obj.txt a = java. util. dateb = javax. swing. JFramec = java. util. the objectpoolfactoryexample of the ArrayList enhanced version (you can change the value range configuration file to extobj.txt a = javax. swing. JFrameb = javax. swing. JLabel # set the title of aa % title = Test Titleimport java. io. fileInputStream; import java. lang. reflect. *; import java. util. *; public class ExtendObjectPoolFactory {// defines an object pool with the object name first and the actual object private Map
   
    
ObjectPool = new HashMap
    
     
(); // Defines a method for creating an Object. The program can generate a java Object private Object creatObjet (String clazzName) throws ClassNotFoundException based on the class name provided by passing in a String class name, instantiationException, IllegalAccessException {Class
     Clazz = Class. forName (clazzName); return clazz. newInstance ();} private Properties config = new Properties (); // This method initializes the object pool based on the specified file, it will create the object public void initPool (String fileName) {FileInputStream FD = null; try {FD = new FileInputStream (fileName); config. load (FCM); // System. out. println ("prop. stringPropertyNames (): "+ prop. stringPropertyNames (); // For each retrieved attribute name and attribute value pair, if the attribute name does not contain %, an object is created based on the attribute value, and put the object into the object pool for (String name: co Nfig. stringPropertyNames () {if (! Name. contains ("%") {objectPool. put (name, creatObjet (config. getProperty (name) ;}} catch (Exception e) {System. out. println ("read" + fileName + "exception! ");} Finally {try {if (FS! = Null) {FS. close () ;}} catch (Exception e2) {e2.printStackTrace () ;}}// retrieve an attribute name-attribute value pair for each pair. If the attribute name contains a percent sign (% ), this attribute is used to set the property value for the object // the program will call the corresponding setter method to set the property value public void initPropertyByMethodReflect () throws SecurityException, NoSuchMethodException, expiration, IllegalAccessException, invocationTargetException {for (String name: config. stringPropertyNames () {if (name. contains ("%") {String [] keyAndValue = name. split ("%"); Object target = getObject (keyAndValue [0]); // String mtdName = "set" + keyAndValue [1]. substring (0, 1 ). toUpperCase () + keyAndValue [1]. substring (1); String mtdName = "setTitle"; // same as the preceding statement; // obtain the Class object Class corresponding to its implementation Class through the getClass method of the object
     Clazz = target. getClass (); Method mtd = clazz. getMethod (mtdName, String. class); mtd. invoke (target, config. getProperty (name) ;}}// retrieves the public object getObject (String name) {return objectPool from the Object with the specified name. get (name);} public static void main (String [] args) throws Exception {ExtendObjectPoolFactory ofy = new ExtendObjectPoolFactory (); ofy. initPool ("extObj.txt"); ofy. initPropertyByMethodReflect (); System. out. println (ofy. getObject (""));}}
    
   
  
 

27. Access attribute values through reflection
Import java. lang. reflect. *; import static java. lang. system. *; public class FieldTest {public static void main (String [] args) throws Exception {Person p = new Person (); Class
 
  
PersonClass = Person. class; // use the getDeclaredField method to obtain fieldField namefield = personClass of various controllers. getDeclaredField ("name"); // you can call this operation to cancel the namefield check. setAccessible (true); namefield. set (p, "zpc Week"); Field agefield = personClass. getDeclaredField ("age"); agefield. setAccessible (true); agefield. set (p, 22); out. println (p) ;}} class Person {private String name; private int age; public String toString () {return "Person [name =" + name + ", age = "+ age +"] ";}}// output: Person [name = zpc week, age = 0]
 

28. generics and reflection
import java.util.Date;import javax.swing.JFrame;public class ReflectAndGeneric {public static 
 
   T getInstance(Class
  
    cls){try {return cls.newInstance();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}public static void main(String[] args) {Date d=ReflectAndGeneric.getInstance(Date.class);JFrame jfm=ReflectAndGeneric.getInstance(JFrame.class);}}
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.