Simple Factory mode using reflection principle and application of reflection principle to read data from the database directly into the entity collection

Source: Internet
Author: User

One: Simple factory first learning example of a simple factory is to make a calculator: The first is the interface

Public interface Cal {

Public double Calcu (double num1,double num2);

}

Then the subtraction class implements the compute interface:

public class ADD implements cal{

@Override

Public double Calcu (double num1, double num2) {

return num1+num2;

}

}

Then write a factory class, there is a static method, the original argument is a char type of +-*/And then according to the parameters passed in to select the return subtraction of one of the classes, such as:

public static Cal choice (char pra) {

Switch (PRA) {

Case ' + ': return new Add ();

Case '-': return new Sub ();

Default:return null;

}

}

Now, using the principle of reflection, we can use a simpler approach:

public static Cal Choice (Class clazz) throws Instantiationexception, illegalaccessexception{

Return (Cal) clazz.newinstance ();

}

Then the test:

Reflective plant

@Test

public void Testfactory () throws Instantiationexception, illegalaccessexception{

Cal Cal=factory.choice (Add.class);

System.out.println (Cal. CALCU (10, 20));

}

Second: Using the principle of reflection from the database to read the data directly encapsulated into the entity set we must first have a database corresponding to the entity class, its properties and database fields preferably one by one corresponding, such as: I have a user class, only the Id,age,name field, then:

Public List getList (String sql,class clazz) throws SQLException, Instantiationexception, Illegalaccessexception, securityexception,nosuchfieldexception{

List list=new ArrayList ();

PreparedStatement ps=con.preparestatement (SQL);

ResultSet Rs=ps.executequery ();

while (Rs.next ()) {

Object obj=clazz.newinstance ();//Passing in an instance of a class

for (int i = 1; I <=rs.getmetadata (). getColumnCount (); i++) {//Because rs.get starts from 1, Rs.getmetadata (). getColumnCount () is the number of columns in the header Clazz.getdeclaredfield (); All fields of the given class include private

Field Field=clazz.getdeclaredfield (Rs.getmetadata (). getColumnName (i));

Field.setaccessible (TRUE);//This method sets the access identity so that inaccessible members can be accessed.

Field.set (obj, Rs.getobject (i));//The first parameter is a type, the second argument is a value

}

List.add (obj);

}

return list;

}

Collection of entity classes that read a database with Reflection encapsulation

@Test

public void GetData () throws SecurityException, SQLException, Instantiationexception, Illegalaccessexception, nosuchfieldexception{

String sql= "Select Id,age,name from [user]";

List list=getlist (Sql,user.class);

for (User user:list) {

P (user.getname () + "\ T" +user.getage ());

}

}

I have a database in the user table has a lot of things, the strength of the class needs to read what, if the entity class is inconsistent with the database field, such as the Power class is the ID, the database is user_id, then you can change the SQL query statement to solve the problem, such as "Select ID as USER_ID ". Because a lot of time to use the entity class collection, with this method can be encapsulated any entity class, convenient many! *************************************************************************************************************** In addition reflection can do many things:

Only constructors with parameters are instantiated

@Test

public void Shilihuaaddpara () throws Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception{

Class Clas=user.class;

Constructor[] Cons=clas.getconstructors ();

for (Constructor constructor:cons) {

System.out.println (constructor);

}

User user= (user) cons[0].newinstance (10,20, "haha");

P (User.getage ());

}

Reflection Gets the parent class

@Test

public void Getfather () throws classnotfoundexception{

Class user=class.forname ("Cn.zzz.reflect.User");

P (User.getsuperclass (). GetName ());

}

Reflection Acquisition Interface

@Test

public void Getjiekou () throws ClassNotFoundException, SecurityException, nosuchmethodexception{

Class user=class.forname ("Cn.zzz.reflect.User");

Class[] Clazz=user.getinterfaces ();

for (Class Class1:clazz) {

P (Class1.getname ());

P (Class1.getmethod ("show"));

}

}

Reflection Call Field

@Test

public void Getfilds () throws ClassNotFoundException, SecurityException, Nosuchfieldexception, instantiationexception , illegalaccessexception{

Class user=class.forname ("Cn.zzz.reflect.User");

This is the Get public field

Field[] Fields=user.getfields ();

This is to get all the fields

Field[] Fields=user.getdeclaredfields ();

for (Field field:fields) {

P (Field.getname ());

}

Field Fil=user.getfield ("id");

Object obj=user.newinstance ();

Fil.set (obj, 10); P (fil.get (obj));

}

Reflection Call Method

@Test

public void GetMethods () throws ClassNotFoundException, SecurityException, Nosuchmethodexception, IllegalArgumentException, Illegalaccessexception, InvocationTargetException, instantiationexception{

Class user=class.forname ("Cn.zzz.reflect.User");

Method[] Methods=user.getmethods ();

for (Method method:methods) {

P (Method.getname ());

// }

Method Method=user.getmethod ("Setage", Int.class);

Object obj=user.newinstance ();

Method.invoke (obj, 20);

Method=user.getmethod ("Getage");

Object Ob=method.invoke (obj);

P (OB);

}

public void P (Object obj) {

System.out.println (Obj.tostring ());

}

Simple Factory mode using reflection principle and application of reflection principle to read data from the database directly into the entity collection

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.