Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Java reflection Introduction     - Create Your Own Docker base image in two ways (Linux)

- Using Libreoffice under ubuntu (Linux)

- To build a private Docker registry (Server)

- Linux vi command list (Linux)

- IP configuration under Linux (Linux)

- Install VMware Tools in Debian (Linux)

- How to query the role of Linux services (Linux)

- Implement binary search algorithm in C language (Programming)

- C ++ CBitmap, HBitmap, Bitmap difference and contact (Programming)

- Access.log Apache access log analysis and how to import it into MySQL (Server)

- Oracle archive log full cause abnormal slow database performance (Database)

- PCM audio under Linux (Linux)

- Easy to get hidden administrator account (Linux)

- iSCSI + multipath achieve DM multipath storage (Server)

- Linux Network Programming - signal blocking and shielding (block, unblock) (Programming)

- Postgres-X2 deployment steps (Database)

- Android Application Development: Genymotion can not start solving (Linux)

- Python script file directory traversal examples (Programming)

- A simple shell script for monitoring in Linux (Linux)

- Installation image conversion tool on your Ubuntu Converseen 0.8.1 (Linux)

 
         
  Java reflection Introduction
     
  Add Date : 2017-01-08      
         
         
         
  Java is a reflection of a very important mechanism, also known as reflection. It allows Java running on their own inspection and internal property or method can directly operate the program.

Reflection mechanism commonly used in class

Reflection api had a lot of inside information include: package, type parameters, superclass, implemented interfaces, inner classes, outer classes, fields, constructors, methods, modifiers, etc.
Common classes include:

Class: indicate a specific class or interface
Constructor: encapsulates the class constructor
Method: The method of providing information about the class or interface
Field: provides information about the properties of a class or interface, and dynamic access to his
Class categories:

Class is itself a class, Class is the name of the class, but also the starting point for reflection;
Get Class methods are:

getClass (): call the specified class object to call through; such as: Class cl = str.getClass () assume str is a String object, as String class properties
getSuperClass (): call by Class class; such as: Class clsup = cl.getSuperClass () as String parent class Object, the class attribute this to get to Object
Class.forName (): Class static method, the class name as a parameter called: If Class cl2 = Class.forName ( "java.lang.String"); Note: This class to load
.Class: Through the class name to call: eg: Class cl3 = String.Class; Note: This is not to load the class
Call the method of packaging:: Basic type TYPE Syntax Class cl4 = Integer.TYPE
The main methods are:

1, public static Class forName (String className) < ?>: Natice method dynamically load classes. Very important.
       As sql dynamically load drivers: class.forName (sqlDriver);
2, public T newInstance (): Create a new object based on the class object for reflection. Very important.
       Available build objects in reflection, call object methods:
       class doubleClass = class.forName ( "java.lang.Double");
       Object objDouble = doubleClass.newInstance ();
       As javaBean in respect of the application of this method, because the default java have a no-argument constructor.
3, public ClassLoader getClassLoader (): get the class of the class loader Bootstrap, Extension, System or user custom ClassLoader (typically system classloader). important.
4, public String getName (): Get the name of the class or interface. Remember enum class, annotation for the interface. important
5, public native Class getSuperclass (): Gets parent class inherits the parent returns the parent class, otherwise returns java.lang.Object. Returns the parent Object null -null. general
6, public java.net.URL getResource (String name): access to resources based on a string.
7, other classes
public boolean isEnum (): determine whether the enumerated type.
public native boolean isArray (): determine whether the array type.
public native boolean isPrimitive (): determine whether the basic types.
public boolean isAnnotation (): determine whether the types of annotations.
public Package getPackage (): reflection obtained package, the package is as java.lang.Object java.lang.
public native int getModifiers (): reflection obtained modifiers, such as public static void like.
public Field getField (String name): reflex obtained domain members.
public Field [] getFields (): obtain the domain Array members.
public Method [] getMethods (): method of obtaining.
public Method getDeclaredMethod (String name, Class ... parameterTypes ): add Declared on behalf of the class, inheritance, the parent class are not included.
public Constructor [] getConstructors () : get all constructor.
Constructor class

Get constructor: Method provided in Class category;

Constructor getConstructor (Class [] params) according to constructor arguments, returning a specific property has public constructor
Constructor getConstructors () function returns an array structure having all public property
Constructor getDeclaredConstructor (Class [] params) according to constructor arguments, returns a specific constructor (regardless of public and non-public property)
Constructor getDeclaredConstructors () Returns the class of all array constructor (regardless of public and non-public property)
The main methods are:

public String getName (): Get the name of the constructor.
public native int getModifiers (): reflection obtained modifiers, such as public static void like.
getParameterTypes (): get the parameter properties
newInstance (Object ... initargs): Use the constructor creates an instance
Method categories:

Constructor method and get the same there are four ways:

Method getMethod (String name, Class [] params) according to the method name and parameters, return to a specific method of public property
Method [] getMethods () method returns an array with all public property, including public methods inherited from the parent class public and implement the interface method
Method getDeclaredMethod (String name, Class [] params) according to the method name and parameters, return to a specific method (regardless of public and non-public property)
Method [] getDeclaredMethods () method returns an array of all (regardless of public and non-public property) are not included in the class inherited from the parent class.
The main methods are:


public String getName (): Get the name of the constructor.
public native int getModifiers (): reflection obtained modifiers, such as public static void like.
getParameterTypes (): get the parameter properties
getReturnType (): Returns the value of the property obtained
invoke (Object obj, Object ... args): The first object parameter for the method, and the second parameter; the most important ways;
Field categories:

Get Field: Method provided in Class category;

Field getField (String name) according to the variable name, returns a specific member variables having public property
Field [] getFields () returns an array of public member variables properties
Field getDeclaredField (String name) according to the variable name, returns a member variable (regardless of public and non-public property)
Field [] getDelcaredField () returns an array of all the member variables (regardless of public and non-public property)
Main methods are: Field class methods are more, not translated, but can know by name usage

Object get (Object obj)
Returns the value of the field represented by this Field, on the specified object.
   
boolean getBoolean (Object obj)
Gets the value of a static or instance boolean field.
   
byte getByte (Object obj)
Gets the value of a static or instance byte field.
   
char getChar (Object obj)
Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion.
    
Class GetDeclaringClass ()
Returns the Class object representing the class or interface that declares the field represented by this Fieldobject.
   
double getDouble (Object obj)
Gets the value of a static or instance field of type double or of another primitive type convertible to type doublevia a widening conversion.
   
float getFloat (Object obj)
Gets the value of a static or instance field of type float or of another primitive type convertible to type floatvia a widening conversion.
   
Type getGenericType ()
Returns a Type object that represents the declared type for the field represented by this Field object.
   
int getInt (Object obj)
Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.
   
long getLong (Object obj)
Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion.
   
int getModifiers ()
Returns the Java language modifiers for the field represented by this Field object, as an integer.
   
String getName ()
Returns the name of the field represented by this Field object.
   
short getShort (Object obj)
Gets the value of a static or instance field of type short or of another primitive type convertible to type shortvia a widening conversion.
   
Class GetType ()
Returns a Class object that identifies the declared type for the field represented by this Field object.
   
boolean isEnumConstant ()
Returns true if this field represents an element of an enumerated type; returns false otherwise.
   
boolean isSynthetic ()
Returns true if this field is a synthetic field; returns false otherwise.
   
void set (Object obj, Object value)
Sets the field represented by this Field object on the specified object argument to the specified new value.
   
void setBoolean (Object obj, boolean z)
Sets the value of a field as a boolean on the specified object.
   
void setByte (Object obj, byte b)
Sets the value of a field as a byte on the specified object.
   
void setChar (Object obj, char c)
Sets the value of a field as a char on the specified object.
   
void setDouble (Object obj, double d)
Sets the value of a field as a double on the specified object.
   
void setFloat (Object obj, float f)
Sets the value of a field as a float on the specified object.
   
void setInt (Object obj, int i)
Sets the value of a field as an int on the specified object.
   
void setLong (Object obj, long l)
Sets the value of a field as a long on the specified object.
   
void setShort (Object obj, short s)
Sets the value of a field as a short on the specified object.
   
String toGenericString ()
Returns a string describing this Field, including its generic type.

Following a brief presentation, details see Note:

package net.peace.ref;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack;

public class TestRef {

public static void main (String [] args) {
// TODO Auto-generated method stub
// Stack < E>
       try {
    // Load the specified class
Class < Stack> c = (Class < Stack>) Class.forName ( "java.util.Stack");
// Get the class name of the specified methods;
Method ms [] = c.getDeclaredMethods ();
// Determine whether a particular class
System.out.println (c.isInstance (new Stack <> ()));
for (Method m: ms) {
// Get some information methods;
System.out.println (m.getModifiers () + "" + m.getReturnType () + "" + m.getName ());
// Get the parameter attribute class
Class [] cc = m.getParameterTypes ();
for (Class p: cc) {
// Get the class name
System.out.println (p.getName ());
}
// Get an exception class
Class [] ce = m.getExceptionTypes ();
for (Class p: ce) {
System.out.println (p.getName ());
}
}
System.out.println ( "******************************");
// Get the constructor method
Constructor [] con = (Constructor []) c.getDeclaredConstructors ();
for (Constructor p: con) {
System.out.println (p);
}
System.out.println ( "******************************");
// Get domain
Field [] field = c.getDeclaredFields ();
for (Field f: field) {
System.out.println (f);
}
} Catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
       System.out.println ( "******************************");
       try {
    // Create an object other than the default constructor by reflection
Class list = Class.forName ( "java.util.ArrayList");
// Set the parameter type
Class ps [] = new Class [1];
ps [0] = Integer.TYPE;
// Get the corresponding parameter of the constructor
Constructor cons = list.getConstructor (ps);
// Construct object by calling the constructor
Integer [] os = {3};
ArrayList t = (ArrayList) cons.newInstance (os);
t.add (1);
System.out.println (t.size ());
// Call the method using reflection
// Create a parameter
Class ps3 [] = new Class [1];
ps3 [0] = Object.class;
// Get the desired method add
Method method1 = list.getDeclaredMethod ( "add", ps3);
// Add an element called 2;
method1.invoke (t, 2); // The first parameter is the object, the second parameter is a method parameter;
/// Call another constructor
Class ps2 [] = new Class [1];
ps2 [0] = Collection.class;
Constructor cons2 = list.getConstructor (ps2);
ArrayList t2 = (ArrayList) cons2.newInstance (t);
System.out.println (t2);

} Catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} Catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} Catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} Catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} Catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} Catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
} Catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
       
}

}
     
         
         
         
  More:      
 
- top command causes the system load increases (Linux)
- Linux Regular expressions grep and egrep (Linux)
- CentOS / Linux restart active NIC connection paths / network configure error Error Resolution (Linux)
- Linux compiler installation Redis (Database)
- Linux bash: scp: command not found the problem (Linux)
- Install Mac OS X 10.9 systems VMware10 (Linux)
- Getting Started with Linux system to learn: how to check the version of SSH on Linux (Linux)
- Wireshark basic introduction and learning TCP three-way handshake (Linux)
- Open MySQL slow query log (Database)
- Enterprise Encrypting File System eCryptfs Comments (Linux)
- Nginx request processing (Server)
- CentOS cross compiler core Raspberry Pi 2 (Linux)
- JavaScript cross-browser event object library (Programming)
- The maximum subsequence algorithm and optimization problems (Programming)
- iOS development -Launch Image and Launchscreen (Programming)
- C ++ 11 feature: decltype keywords (Programming)
- Mass data storage application of MongoDB database (Database)
- To restore the last time applications running when Ubuntu user log in again (Linux)
- Nagios plugin installation tutorial of Nrpe (Linux)
- Linux Telnet access Windows 7 configuration procedure (Linux)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.