Some new features of deep Java7 and an introduction to scripting language support APIs _java

Source: Internet
Author: User
Tags eval reflection java se advantage

A string can be added to the 1.switch conditional statement by using the literal value of the hashcode () value job of the string
2. Added a system that can be used in the literal, binary, by adding "0b" or "0B" to the front of the number
3. Use underscores in numeric literals to separate numbers for easy reading without affecting the size of the values. The basic principle is that both front and back are numbers before the underline can appear.
4.java7 made two changes to the exception:

  4.1. supports capturing multiple exceptions in one catch clause while the other is more precise when the exception is caught and thrown back. The Throwable class in Java7 adds the Addsuppressed method, and when an exception is thrown, there may be other exceptions that are suppressed because of the exception and cannot be thrown properly. These suppressed methods can then be recorded by the Addsuppressed method, and the suppressed exceptions appear in the stack information of the thrown exception, or they can be obtained by the getsuppressed method. The advantage of doing this is that no exceptions will be lost to facilitate developer testing.

Copy Code code as follows:

public class ReadFile () {
public void read (String filename) throws IOException {
FileInputStream input = null;
IOException readexception = null;
try {
input = new FileInputStream (filename);
catch (IOException ex) {
Readexception = ex;
finally {
if (input!= null) {
try {
Input.close ();
catch (IOException ex) {
if (readexception!= null) {
Readexception.addsuppressed (ex);
} else {
Readexception = ex;
}
}
}
if (readexception!= null) {
Throw readexception;
}
}
}


The key to this approach is to add the exception generated in the finally statement through the Addsuppressed method to the exception generated by the try statement.


Java7 improves the syntax of catch clauses, allowing you to specify a variety of exceptions, using "|" Between each exception type to separate. Note that the caught exceptions are declared in the catch clause, the duplicate type cannot occur, and one of the exceptions is not allowed to be a subclass of another exception parameter, or there will be a compilation error (no problem from small to upper case). If multiple exceptions are declared in a catch clause, the specific type of the exception parameter is the minimum upper bound of all of these exception types.

  4.2 uses a try (request resources) {Business Processing} to automatically release resources, and the resources that can be managed by a try statement need to meet a condition that its Java class implements the Java.lang.AutoCloseable interface, otherwise a compilation error occurs. The Close method of the interface is invoked automatically when the resource needs to be freed.

5. Method calls to optimize variable-length parameters:
A new feature introduced in j2se5.0 is to allow variable-length parameters to be used in method declarations. The last form parameter of a method can be specified to represent any number of parameters of the same type. When invoked, these parameters are passed in the form of an array. You can also refer to these parameters as arrays in the method body.

6. Java7 introduced a new annotation @safevarargs. If the developer is convinced that a method using variable-length parameters does not appear similar to the one used with the generic class, it can be declared with this annotation. @SafeVarargs annotations can only be used on methods or construction methods that have variable parameter lengths, and the method must be declared static or final, or a compilation error occurs. One way to use @safevarargs annotations is for developers to ensure that the processing of generic type parameters in the implementation of this method does not raise type-safety issues.

In 7.java, some scripting languages are supported in Java virtual machines through scripting engines. In fact, the scripting engine Manager supports a total of three search engines, respectively, by name, file extension, and MIME type. Such as

Copy Code code as follows:

public void greet () throws Scriptexception {
Scriptenginemanager manager = new Scriptenginemanager ();
ScriptEngine engine = Manager.getenginebyname ("JavaScript");
if (engine = = null) {
throw new RuntimeException ("Cannot find JavaScript language execution engine");
}
Engine.eval ("println (' Hello ');");
}

It can also be found by Getengingbyextension ("JS") and Getenginebymimetype ("Text/javascript"). After you get the object that the script engine ScriptEngine, you can execute a piece of code through its Eval method and return the execution result of that code.

7.1 Language bindings:
One of the great advantages of scripting language support APIs is that it regulates the way the Java language interacts with scripting languages, enabling programs written in the Java language to make two-way method calls and data transfers between scripts. Data transfer is done through language-bound objects. The so-called language binding object is a simple hash table for storing and retrieving data that needs to be shared. All data corresponds to an entry in this hash table and is a simple name-value pair. Interface Javax.script.Bingings defines the interface of a language-bound object, which inherits from the Java.util.Map interface. A script engine may use more than one language binding object during execution. Different language bound objects have different scopes. By default, the scripting engine provides multiple language binding objects to hold the global objects that are generated during execution. The Scriptenging class provides the put and get methods to manipulate the default language-bound objects that are specific to the script engine. Programs can use this default language binding object directly, or you can use your own language to bind objects. During script execution, you can consider a language-bound object as an additional variable mapping table. When you parse the value of a variable, the name in the language-bound object is also taken into account. The contents of the global variables generated during the execution of the script appear in the language-bound object. In this way, the bidirectional data transfer between Java and the scripting language is accomplished.
If you add a string named "name" to the script engine default language binding object by using the ScriptEngine put method, the object is referenced directly by name in the script. Similarly, the global variable "message" created in the script can also be obtained through the scriptenging get method. This enables bidirectional data transfer between Java programs and scripts. Type conversions in the data transfer process are done by the scripting engine, and the conversion rules depend on the syntax of the specific language

Copy Code code as follows:

public void Usedefaultbinging () throws Scriptexception {
Scriptenginemanager manager = new Scriptenginemanager ();
ScriptEngine engine = Manager.getenginebyname ("JavaScript");
ScriptEngine engine = getjavascriptenging ();
Engine.put ("Name", "World");
Engine.eval ("var message = ' Hello, ' +name;");
Engine.eval ("println (Message)");
Object obj = engine.get ("message");
System.out.println (obj);
}

In most cases, using Scriptenging's put and get methods is sufficient. If you use the put and get methods only, the language-bound object itself is transparent to the developer. In some cases, you need to use the program's own language-bound object, such as a language-bound object that contains data unique to the program. If you want to bind objects in your own language, you can call the script engine's Creatbingings method or create a Javax.script.SimpleBingings object, and pass the Eval method to the script engine as:

Copy Code code as follows:

public void Usecustombinding () throws Scriptexception
{
ScriptEngine engine = Getjavascriptengine ();
Bindings bindings = new Simplebindings ();
Bindings.put ("hobby", "play games");
Engine.eval ("println" (' I like ' +hobby); ", bindings);
}

The language-bound object passed through the Eval method, which takes effect only in the current eval call, and does not change the engine default language binding object

7.2 Script Execution context
Another important interface associated with scripting engine execution is Javax.script.ScriptContext, which contains contextual information during script engine execution. An analogy can be made with the Javax.servlet.ServletContext interface in the servlet specification in Java EE. The script engine obtains information about the execution of the script through the primer context object, and allows developers to configure the behavior of the script engine through this object. The top and bottom objects contain the following 3 types of information.
7.2.1 Input and output
First, the configuration information related to script input and output is introduced, including the Java.io.Reader object that the script uses to read data input in execution, and the Java.io.Writer object that outputs the correct content and error information. By default, the input and output of the script occurs in the standard console, and if you want to write the output of the script to a file, you can use the following code. The output of the script is redirected to a file through the Setwriter method. The ScriptContext Setreader and Seterrorwriter methods can be used to set the source of the data input when the script executes and the output of the error message when the errors are generated.

Copy Code code as follows:

public void Scripttofile () throws ioexception,scriptexception{
ScriptEngine engine = Getjavascriptengine ();
ScriptContext context = Engine.getcontext ();
Context.setwriter (New FileWriter ("output.txt"));
Engine.eval ("println (' Hello world! ');");
}

7.2.2 Custom Properties

ScriptContext also has a similar method of obtaining and setting properties in ServletContext, that is, setattribute and getattribute. The difference is that the attributes in ScriptContext are scoped. Different scopes differ in the order in which they are searched, and each scope represents their lookup order in a corresponding integer. The smaller the integer value, the higher the order in which the lookup takes precedence. Attributes in a higher priority scope hide the same name in the lower priority. For this reason, you need to explicitly specify the scope of the property when you set it. When you get a property, you can select a lookup in the specified scope, or you may choose to automatically find it based on the scope priority.
However, the scope contained in the execution context implementation of the script is fixed. Developers are not free to define their scopes. The ScriptContext Getscopes method allows you to get a list of all the scopes available. There are two scopes predefined in Sciptcontext: The scope of the constant Scriptcontext.engine_scope represents the current scripting engine, and Scriptcontext.global_ Scope represents a scope that corresponds to all script engine objects created from the same engine factory. The former has a higher priority. The following example:

Copy Code code as follows:

public void Scriptcontextattribute () {
ScriptEngine engine = getjavascriptenging ();
ScriptContext context = Engine.getcontext ();
Context.setattribute ("Name", "World", Scriptcontext.global_scope);
Context.setattribute ("name", "Bob", Scriptcontext.engine_scope);
Context.getattribute ("name");//value is Bob
}

7.2.3 Language Binding Object

The last type of information in the script execution context is the language binding object. Language-bound objects also correspond to scopes. The same scope-priority order applies to language-bound objects. This order of precedence has an effect on the resolution of the variables at the time the script executes. The following example:

Copy Code code as follows:

public void Scriptcontextbindings () throws Scriptexception
{
ScriptEngine engine = getjavascriptenging ();
ScriptContext context = Engine.getcontext ();
Bindings bindings1 = Engine.createbindings ();
Bindings1.put ("Name", "World");
Context.setbindings (Bindings1,scriptcontext.global_scope);
Bindings BINDINGS2 = Engine.createbindings ();
Bindings2.put ("name", "Bob");
Context.setbindings (Bindings2,scriptcontext.engine_scope);
Engine.eval ("println (name);"); /result is Bob
}

can also bindings bindings = Context.getbindings (Scriptcontext.engine_scope);

Bindings.put ("Name", "World")
Engine.eval ("println (name);");

7.3 Compilation of scripts:
Scripting languages are generally interpreted as execution. The script engine needs to parse the script before executing it at run time. In general, it is slower to run a script by interpreting execution than after compiling it. When a script needs to be repeated multiple times, you can compile the script first. The execution of a compiled script does not require repeated parsing, which can improve efficiency. Not all script engines support compiling scripts. If the scripting engine supports this feature, it implements the Javax.script.Compilable interface to declare this. Users of the script engine can take advantage of this ability to improve the efficiency of scripts that need to be executed more than once. The JavaScript script engine that is brought in Java SE supports the compilation of scripts.
In the following code, the compile method of the Compilable interface is used to compile the script code, and the result of the compilation is expressed in Javax.script.CompiledScript. Since not all scripting engines support the Compilable interface, it is necessary to use instanceof for judgment. In the Run method, you can execute the script by using the Compiledscript eval method. The code repeats a script 100 times to illustrate the performance advantage of the compiled script as it repeats.

Copy Code code as follows:

Public Compiledscript compile (String scripttext) throws Scriptexception {
ScriptEngine engine = Getjavascriptengine ();
if (engine instanceof compilable) {
Compiledscript script = ((compilable) engine). Compile (ScriptText);
}
return null;
}

public void Run (String scripttext) throws Scriptexception {
Compiledscript script = compile (scripttext);
if (script = = null) {
Return
}
for (int i = 0; i < i++) {
Script.eval ();
}
}


The Compiledscript eval method accepts parameters that are the same as the ScriptEngine eval method.

7.4 Method calls in script
In the script, the most common and most practical is the method. Some script engines allow a user to invoke a method in the script individually. Scripting engines that support this method invocation can implement the Javax.script.Invocable interface. The Invocable interface allows you to invoke the top-level method in the script, or you can call the member methods in the object. If the member method in the top-level method or object in the script implements the interface in Java, you can get the implementation object of the corresponding Java interface in the script by using the methods in the Invocable interface. This allows you to define the interface in the Java language and implement the interface in the script. Other parts of the code that use the interface in the program do not know that the interface is implemented by the script. As with the Compilable interface, ScriptEngine is optional for the implementation of the Invocable interface.
The following code invokes the top-level method in the script through the invokefunction of the Invocable interface, and the arguments are passed to the method in the script. Because the javase JavaScript scripting engine implements the Invocable interface, this eliminates the judgment that the engine implements the Invocalbe interface
Examples of calling script top-level methods in Java:

Copy Code code as follows:

public void Invokefunction () throws scriptexception,nosuchmethodexception{
ScriptEngine engine = Getjavascriptengine ();
String ScriptText = "function greet (name) {println (' Hello, ' +name);}";
Engine.eval (ScriptText);
Invocable invocable= (invocable) engine;
Invocable.invokefunction ("Greet", "World");
}

If the invoked method is a member method of the object in the script, you need to use the InvokeMethod method, as shown in the following code, where the GetGreeting method belongs to object obj, which needs to be passed in as a parameter when invoked.

Example of calling a member method of a script object in Java

Copy Code code as follows:

public void Inokemethod () throws Scriptexception,nosuchmethodexception
{
ScriptEngine engine = Getjavascriptengine ();
String ScriptText = "var obj={getgreeting:function (name) {return ' Hello, ' +name;}};";
Engine.eval (ScriptText);
Invocable invocable = (invocable) engine;
Object scope = engine.get ("obj");
Object result = Invocable.invokemethod (scope, "getgreeting", "alxx");
SYSTEM.OUT.PRINTLN (result);
}

Method InvokeMethod is similar to method invokefunction usage, except InvokeMethod to specify the object containing the method to be called.

Java interface implementation in 7.5 scripts

In some scripting engines, you can define an interface in the Java language and write an implementation of the interface in a script, so that other parts of the program can interact with the Java interface only and do not need to care how the interface is implemented. In the following code greet is a Java-defined interface that contains a getgreeting method. This interface is implemented in the script, and the GetInterface method is used to get the object of this interface implemented by the script and to invoke the method.

Copy Code code as follows:

public void Useinterface () throws Scriptexception {
ScriptEngine engine = Getjavascriptengine ();
String ScriptText = "function getgreeting (name) {return ' Hello, ' +name;} ';
Engine.eval (ScriptText);
Invocable invocable = (invocable) engine;
Greet Greet = Invocable.getinterface (Greet.class);
System.out.println (Greet.getgreeting ("World"));
}

The implementation of the interface in the above is done by the top-level method in the script. Similarly, it can be implemented by the member methods of the objects in the script. In this case, another overloaded form of the GetInterface method can accept an additional parameter to specify the object in which the interface implementation resides.

Because the syntax of the scripting language is simple and flexible, it is very suitable for users who have no or only a small number of programming backgrounds, these users can customize the business logic and user interface of the program through scripting language, and the scripting language can achieve a better balance between the ease of use and flexibility of the program. For example, the scripting language Lua is widely used in game development to customize the game's internal behavior and user interface.

8. The reflection API, while providing flexibility for Java programs, also generates additional performance costs, due to the implementation mechanism of the reflection API, for the same operations, such as invoking a method, using the reflection API to dynamically implement a two order of magnitude slower than the one written directly in the source code. As the implementation of Java virtual machines improves, the performance of the reflection API has been greatly improved. However, this performance gap is objective, therefore, in some of the higher performance requirements of applications, be cautious to use the reflection API.

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.