JAVA basics: Find the class name from the. class File

Source: Internet
Author: User
JAVA basics: Find the class name-general Linux technology-Linux programming and kernel information from the. class file. The following is a detailed description. You can determine the name of a class in multiple ways:

Assume that all classes start with com, org, or net.
Search for a class named Hack by classpath.
Search for classpath to find the Directory Entry mapped to this file
Directly view the class itself. In all cases, this is the most direct
The Java specification specifies how to view a class file. The first value stored in the class file is the complete class description in the format of the Java internal delimiter.

The following code returns the file C: \ code \ hacks \ research \ com \ generationjava \ Hack. class internal class name com/generationjava/Hack, readers can further write code to convert "/" to ". ":

Static final public int MAGIC = 0 xCAFEBABE;
// Pass C: \ code \ hacks \ research \ com \ generationjava \ Hack. class
// Assume that such a class exists.
Public String getFullyQualifiedName (String filename) throws IOException {
String name = null;

Try {
DataInputStream in = new
DataInputStream (new FileInputStream (filename ));
If (in. readInt ()! = MAGIC ){
// Not a. class File
Thrownew IOException ("Not a class file ");
}

In. readUnsignedShort (); // version number
In. readUnsignedShort (); // main version number
In. readUnsignedShort (); // Length
In. readByte (); // CLASS = 7
In. readUnsignedShort (); // ignore this location
In. readByte (); // UTF8 = 1
Name = in. readUTF (); // class name !!!
In. close ();
} Catch (IOException ioe ){
Ioe. printStackTrace ();
}

Return name;
}
When you directly obtain class information from the. class file, the development is simplified. Finding the complete class name of an anonymous. class file is an important part of any. class file-based application.

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.