Java Foundation Enhancement

Source: Internet
Author: User
Tags throwable

*0-Generic design
A) generics are just a constraint at the source level (. java) at the bytecode level (. Class) that constrains the "erase"
b) very similar to code for multiple DAO
c) Write a Basedao class that allows the specific class to extend its corresponding method, but cannot introduce any variable of the specific type in the Basedao
D) You can assign a value to an instance variable by constructing a method

* Reflection Generics
Get Basedao byte-code object
Class Basedaoclass = This.getclass ();
Gets the generic type of the Basedao
Type type = (type) basedaoclass.getgenericsuperclass ();
To forward the type to parameterizedtype, that is to get the parameterized type of basedao<type>
Parameterizedtype pt = (parameterizedtype) type;
Gets the instance parameter type in the parameterized type, that is, type
This.clazz = (Class) pt.getactualtypearguments () [0];
int index = This.clazz.getName (). LastIndexOf (".");
Table name
This.tablename = This.clazz.getName (). substring (index+1). toLowerCase ();

basedao<t> generic type
basedao<type> parameterized types


2 Annotation (note @)
a)///**//** */javadoc Note to the programmer, the annotations are for the compiler to see.
B) There are three basic annotations in the JDK
@Override (methods to detect whether the parent class is overwritten)
@Deprecated (identifying the method is obsolete)
@SuppressWarnings ("Unchecked") (Suppress compiler Warning)
or
@SuppressWarnings (value={"Unchecked"}) (suppress compiler do not warn)
C) Annotations:
General remarks: Annotations of the Adornment method.
Meta-Annotations: annotations that modify annotations.
Custom Annotations and reflection annotations
a) define the annotation format as follows:
//Custom annotations
Public @interface myannotation {
//Properties
String who ();
int age ();
String Gender ();
//Annotations no Method
}

//annotations using
@MyAnnotation (who= "Merry", Age=20, gender= "man")

b) Set default values for annotations
Public @interface Youannotation {
String who () default "marry";
int age () default 22;
String gender () default "female";
}

Annotations Use
@YouAnnotation
Or
@YouAnnotation (who= "Sisi", age=21, gender= "male")//Overwrite all default properties
Or
@YouAnnotation (who= "Sisi")//override partial default properties
c) Array Condition:
Public @interface Theyannotation {
String[] Value (); Value is a special attribute that can omit the value name
}
Annotations Use
@TheyAnnotation (value={"TV", "Washing Machine", "Computer"})
Or
@TheyAnnotation ({"TV", "Washing Machine", "Computer"})

d) Reflection annotations: Annotations can be used to some extent to override parameters, property files, XML files

Code
Annotation class
@Target (Elementtype.method)
@Retention (Retentionpolicy.runtime)
Public @interface Role {
String username () default "Jack";
String password () default "123456";
}

Using the Annotation class
public class Annotationdemo {
public static void Main (string[] args) throws Nosuchmethodexception, SecurityException {
Boolean flag = isOk ("Merry", "123");
SYSTEM.OUT.PRINTLN (flag);
Flag = IsOk ("Jack", "123456");
SYSTEM.OUT.PRINTLN (flag);

}

@Role
private static Boolean IsOk (string Username, string password) throws Nosuchmethodexception, SecurityException {
Reflection annotations
Class clazz = Annotationdemo.class;
method = Clazz.getdeclaredmethod ("IsOk", String.class, String.class);
Role role = Method.getannotation (Role.class);
String annusername = Role.username ();
String Annpassword = Role.password ();
if (Username.equals (annusername) && password.equals (Annpassword)) return true;
return false;
}
}

e) Strategies for annotations [@Retention]
1) Retentionpolicy.source: Visible at the source level, not visible at the bytecode level and at run time, cannot be reflected
2) Retentionpolicy.class: (default) Byte code level visible, not visible at run time, cannot be reflected
3) Retentionpolicy.runtime: Runtime visible, can be reflected, that is, at the source and class level have

f) identify where annotations can be used [@Target]
Elementtype.type, Elementtype.field, Elementtype.method, Elementtype.parameter, Elementtype.construction, Elementtype.local_variable

g) Write document [@Documented]
The Annation class that is modified by the meta-annotation will be extracted as a document by the Javadoc tool.

h) Increased inheritance [@Inherited]
The annotation class that it modifies will have inheritance. That
If a class uses the @inherited decorated annotation class, the subclasses of the annotated class also inherit the annotations corresponding to the parent class.
Note: Meta annotations can modify other annotations, and meta annotations themselves can be modified by other meta annotations or by themselves


Agent
A) static proxy (a proxy class uniquely proxies an object)
Why would there be an agent?
Block direct access to the target object
How to proxy?
In the proxy object, write a business method that is the same as the target object
Code
Star interface
Public interface Star {
public void Sing ();
}
Star Jack
public class Starjack implements Star {

@Override
public void Sing () {
System.out.println ("singing");
}
}
Star Jack Agent
public class Jackproxy implements star{
Private Starjack Jack = new Starjack ();
@Override
public void Sing () {
Jack.sing ();
}
Get the star Jack entity
Public Star GetProxy () {
return Jack;
}
}
Fans
public class Fans {
public static void Main (string[] args) {
Get the star Jack's agent
Jackproxy proxy = new Jackproxy ();
Get Jack Object by proxy
Starjack Jack = (starjack) proxy.getproxy ();
Jack sings.
Jack.sing ();
}
}

b) Dynamic proxy (a proxy class can proxy multiple objects)
Development steps for the proxy class:
1) write a generic class without any inheritance or implementation
2) Write an instance variable that is the target instance object for the agent
3) Assigning a value to an instance variable using a construction method
4) Write a common method, the return value of the method is the interface, the interface is the implementation of the target object interface
Code
Star interface
Public interface Star {
Public String Sing (Integer money);
public void Dance (Integer money, String name);
public void Run (Integer money);
}

Star Jack
public class Starjack implements star{
@Override
Public String Sing (Integer money) {
System.out.println ("singing");
Return "Thank you";
}

@Override
public void Dance (Integer money, String name) {
System.out.println ("Jack Dances:" + name);
}

@Override
public void Run (Integer money) {
SYSTEM.OUT.PRINTLN ("Running!");
}
}


Jack, Agent.
public class Jackproxy {

Private Starjack Jack = new Starjack ();

Parameter one: Class loader for proxy classes
Parameter two: interface of the target class of the agent
Parameter three: An interception class that represents a dynamic proxy object that executes the Invoke () method of this class each time the target object is called.
Public Star GetProxy () {
Meaning of the three parameters of the Invoke () method
Parameter one: The dynamically generated proxy object itself, here is the Jackproxy instance object proxy
Parameter two: method that means to call
Parameter three: args represents the parameters of the calling method
Return value: The return value of the method for the class of the proxy.
Star star = (Star) proxy.newproxyinstance (
JackProxy.class.getClassLoader (),
Jack.getclass (). Getinterfaces (),
New Invocationhandler () {

@Override
public object invoke (object proxy, Method method, object[] args) throws Throwable {
System.out.println (Method.getname ());//sing
System.out.println (Args[0]);//200
Integer money = (integer) args[0];
if (money< 200) {
System.out.println ("Not Enough money!");
} else {
if ("Sing". Equals (Method.getname ())) {
String returnvalue = (string) method.invoke (Jack, args);
System.out.println (returnvalue);//Thank you!
} else if ("Dance". Equals (Method.getname ())) {
Method.invoke (Jack, args);
} else if ("Run". Equals (Method.getname ())) {
System.out.println ("There is something today, no running!") ");
}
}
return null;
}
});
Return star;
}
}

Fans
public class Fans {
public static void Main (string[] args) {
Jackproxy proxy = new Jackproxy ();
Star star = Proxy.getproxy ();
Star.sing (180);//Not enough money!
Star.sing (200);//Sing Thank you
Star.dance (200),//jack dance: Cha am Dance
Star.run (200);//have something to do today, don't run!
}
}


5 Dynamic Agent Case
1) solve the unified coding problem of the website post and get
Code
Jsp
Get mode: <a href= "${pagecontext.request.contextpath}/login?username=<%=urlencoder.encode (" Jack "," Utf-8 ")%> &password=123456 "> Login </a>
Post mode:
<form method= "POST" action= "${pagecontext.request.contextpath}/login" >
<input type= "text" name= "username"/><br/>
<input type= "password" name= "password"/> <br/>
<input type= "Submit" vlaue= "Submission" >
</form>

Filter
public class Encoderfilter implements Filter {
@Override
public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {
Requestproxy proxy = new Requestproxy (request);
Chain.dofilter (Proxy.getproxy (), response);
}
@Override
public void Destroy () {
}
@Override
public void init (Filterconfig arg0) throws Servletexception {
}

}

//proxy

public class Requestproxy {

Private HttpServletRequest request;

Public Requestproxy (ServletRequest request) {
This.request = (httpservletrequest) request;
}

Public HttpServletRequest getproxy () {///return value must be an interface
return (httpservletrequest) proxy.newproxyinstance ( RequestProxy.class.getClassLoader (),
Request.getclass (). Getinterfaces (),
New Invocationhandler () {
@ Override
Public Object Invoke (object proxy, method, object[] args) throws Throwable {
String Funmethod = Meth Od.getname ();
if ("GetParameter". Equals (Funmethod)) {
String Requestmethod = Request.getmethod ();
if ("GET". Equals (Requestmethod)) {
String data = Request.getparameter ((String) args[0]);
byte[] Userbuf = data.getbytes ("iso8859-1");
data = new String (userbuf, "UTF-8"); The
return data;//this return value, which is the return value of the method that is called for the Proxied object.
} else {
request.setcharacterencoding ("UTF-8");
return Method.invoke (request, args);
}
} else {
return Method.invoke (request, args);
}
}
});
}

}


Servlet
public class Loginservlet extends HttpServlet {
@Override
protected void Doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
String username = req.getparameter ("username");
String Password = req.getparameter ("password");
SYSTEM.OUT.PRINTLN (username + ":" + password);
}
@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
String username = req.getparameter ("username");
String Password = req.getparameter ("password");
SYSTEM.OUT.PRINTLN (username + ":" + password);
}
}

2) solve the problem of website output stream compression
Code
3) Resolve proxy issues that return connection objects in the site
Code
Custom connection Pooling
public class Pool {
private static linkedlist<connection> LinkedList = new linkedlist<connection> ();
static{
When the pool class is loaded, 10 connections are created and joined to the connection pool
for (int i=0;i<10;i++) {
try {
Class.forName ("Com.mysql.jdbc.Driver");
Connection conn = drivermanager.getconnection ("Jdbc:mysql://localhost:3306/bbs", "root", "root");
LINKEDLIST.ADDLAST (conn);
} catch (Exception e) {
}
}
}
Gets the number of connections in the connection pool
public int GetSize () {
return Linkedlist.size ();
}
/* Get an idle connection and return only the dynamic proxy object for connection
Public Connection getconnection () {
Final Connection conn = Linkedlist.removefirst ();
Return (Connection) proxy.newproxyinstance (
Pool.class.getClassLoader (),
Conn.getclass (). Getinterfaces (),
New Invocationhandler () {
Public Object Invoke (
Object Proxy,
Method method,
Object[] args) throws Throwable {
If the close () method is called
if ("Close". Equals (Method.getname ())) {
Put the connection back into the connection pool
LINKEDLIST.ADDLAST (conn);
Returns null
return null;
}else{
Return Method.invoke (Conn,args);
}
}
});
}
*/
Public Connection getconnection () {
Connection conn = Linkedlist.removefirst ();
Return conn;//back to True connection
}
}


6 Understanding the characteristics of class loading
The class loader for Java has three layers:
1) Bootstrap Load Core class library (first), that is: Load Jre/lib/rt.jar
2) Extclassloader load non-core auxiliary class library (second), that is: Load jre/lib/ext/*.jar
3) Appclassloader load each application's own class library (last), that is: load all the jars and directories specified by classpath
Each Java program needs to enable the above three class loaders to run


A) overall responsibility
When loading a non-core non-auxiliary class library, if other non-core non-auxiliary classes are involved, the Appclassloader is responsible for loading

b) Delegation mechanism
When a class is loaded, it is first loaded by the parent loader, if all of the parent loaders are not loaded, and finally by self-loading

c) Caching mechanism
When loading a class, if there is a corresponding byte code in the cache beforehand, it is used directly, if not, then temporarily loaded, and then put into the cache after completion to
Make the next reuse

7 Use of URLs and httpurlconnection
1) service End [get]-> mobile phone
(1) The handset sends the request first, then receives the service side response
(2) write to the Get mode on the server side
Code

2) mobile phone--service side [POST]
(1) In the service side write to the post mode
Code

3) for Chinese style:
(1) URL encoding via Urlencoder,
String username = "Jack";
Username = Urlencoder.encode (username, "UTF-8");
(2) Encoding settings on the server:
Request.setcharacterencoding ("UTF-8");
(3) must ensure URL encoding and resolution are consistent

Java Foundation Enhancement

Related Article

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.