Java---annotations, classloader-enhanced-implements an empty parameter method that adds @mytest to a class in any directory

Source: Internet
Author: User

do your own class loader

The core of the virtual machine is to load the. class file through the ClassLoader and perform the corresponding parsing. Then we can do the class loader by ourselves and load the required. Class manually for parsing execution, which extends the functionality of the virtual machine.

The following is excerpted from the API documentation:

Applications need to implement ClassLoader subclasses to extend the way that Java virtual machines load classes dynamically.

The network ClassLoader subclass must define methods Findclass and loadClassData to implement the load class from the network. After you download the bytes that make up the class, it should use method DefineClass to create the class instance.

code example:
Own class loader Myclassloader

 PackageCn.hncu;ImportJava.io.ByteArrayOutputStream;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.IOException;ImportOrg.junit.Test; Public  class myclassloader extends ClassLoader{     PublicClass<?>Findclass(String name) {//name = "E:\\cn\\hncu\\person.class"Class C =NULL; FileInputStream in;byte[] b=NULL;//Read byte-code data into buf[] via IO or network. Further,        //If we are familiar with the generation format of bytecode, we can also build our own programs.         //In this case, we read the data from an external bytecode file in the hard drive to buf[]        //1        Try{in =NewFileInputStream (name);byte[] buf =New byte[1024x768]; Bytearrayoutputstream BAOs =NewBytearrayoutputstream ();//byte stream            intlen=0; while((Len=in.read (BUF))!=-1) {Baos.write (buf,0, Len);            } in.close ();            Baos.close (); b = Baos.tobytearray ();//2---1-2 you can extract it here and write a loadClassData method.}Catch(FileNotFoundException e)        {E.printstacktrace (); }Catch(IOException e)        {E.printstacktrace (); } C = DefineClass ("Cn.hncu.Person"B0, b.length);returnC }@Test     Public void Testclassdata()throwsreflectiveoperationexception{String classname="Cn.hncu.Person";//Load a Java class loader with aClass C = class.forname (ClassName);        Object obj = c.newinstance ();        System.out.println (obj);        SYSTEM.OUT.PRINTLN (person), obj); System.out.println ("-------------------"); ClassName ="E:\\cn\\hncu\\person.class";        Class C2 = Findclass (className);        Object obj2 = C2.newinstance ();        System.out.println (OBJ2); SYSTEM.OUT.PRINTLN (person) obj2);//There is a problem with this sentence.        //※ the objects loaded by different classloader are not strong---can be understood to be different living spaces        //person P2 = (person) obj2;//will hang.         //Because OBJ2 's living space is myclassloader, and the person's spawning space is Appclassloader        //system.out.println (p2);}}

Test results:

Look, the last sentence can not output it.
Because it is not a class loader.

make your own test tool Myjunit
(Case used for annotations and reflection)

Related instructions:

1) JUnit uses @test annotations, and we use @mytest annotations.

2) JUnit has been embedded in the MyEclipse, our own myjunit as long as it can be run independently (without embedding), and it is not convenient for us to receive the class name and method name of the tested class in the Myjunit parameter, can only be received in the form of keyboard input.

3) JUnit can implement a single method to invoke execution, because it cannot take advantage of myeclipse, so we traverse all the methods in the Myjunit program and decide whether to invoke execution of the method by judging whether the @mytest annotation is declared.

Here's how to implement @mytest annotations in any directory running:
You need to enter the absolute pathname and the full name of the class.

NOTES: @MyTest

Package CN. Hncu. Myjunit;Import Java. Lang. Annotation. ElementType;Import Java. Lang. Annotation. Retention;Import Java. Lang. Annotation. Retentionpolicy;Import Java. Lang. Annotation. Target;@Retention (Retentionpolicy. RUNTIME)//Run time also exists, must add this @target (ElementType. METHOD)//Limit annotations can only be added on methods public @interface MyTest {}

Test class: Testperson

 PackageCn.hncu.myJunit;/** * for testing * @author Chen Haoxiang * * @version 1.0 2016-5-6 */ Public  class Testperson {     Public void run1() {System.out.println ("Run1 ..."); }@MyTest     Public void run2() {System.out.println ("Run2 ..."); } Public void Run3() {System.out.println ("Run3 ..."); }@MyTest     Public void Run4() {System.out.println ("Run4 ..."); } Public void Run5() {System.out.println ("Run5 ..."); }}

Myclassloader class: Self-written class loader

 PackageCn.hncu.myJunit;ImportJava.io.ByteArrayOutputStream;ImportJava.io.FileInputStream;ImportJava.io.FileNotFoundException;ImportJava.io.IOException;/** * Self-written class loader * @author Chen Haoxiang * * @version 1.0 2016-5-6 */ Public  class myclassloader extends ClassLoader{//I divided it into 2 ways to write.      PublicClass<?>Findclass(string name, String className) {Try{byteB[] = loadclassdata (name); Class C = defineclass (ClassName, B,0, b.length);returnC }Catch(FileNotFoundException e)        {E.printstacktrace (); }Catch(IOException e)        {E.printstacktrace (); }return NULL; }Private Static byte[]loadClassData(String name)throwsIOException {byteBuf[] =New byte[1024x768]; FileInputStream in =NewFileInputStream (name); Bytearrayoutputstream out =NewBytearrayoutputstream ();intlen=0; while((Len=in.read (BUF))!=-1) {Out.write (buf,0, Len);        } in.close (); Out.close ();byteB[] = Out.tobytearray ();returnb }}

Main Method Class:

 PackageCn.hncu.myJunit;ImportJava.lang.reflect.Method;ImportJava.util.Scanner;ImportCn.hncu.myJunit.MyClassLoader;/** * @author Chen Haoxiang * @version 1.0 2016-5-6 * * Public  class myjunit {     Public Static void Main(string[] args)throwsreflectiveoperationexception {Scanner SC =NewScanner (system.in); System.out.println ("Enter the absolute path of the class you want to run (you cannot have spaces in the path, you need the. class file for the classes):");        String name = Sc.next (); System.out.println ("Please enter the name of the class (including the package name):");        String className = Sc.next (); Class C = (NewMyclassloader ()). Findclass (name, className);//Get that class.         //The class must have an empty parameter construction methodObject obj = c.newinstance ();//Get methods for all declarations of this class, including privateMethod ms[] = C.getdeclaredmethods (); for(Method m:ms) {if(M.isannotationpresent (Mytest.class)) {M.invoke (obj,NULL); }        }    }}

To run the test results:

Now I've moved the class file to the D drive.

Then look at the results of the operation:

This can be a lot of improvements, such as every time the input path is very troublesome,
We can do a graphical interface, let us choose.
This is much more convenient.

Java---annotations, classloader-enhanced-implements an empty parameter method that adds @mytest to a class in any directory

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.