Parse java class file

Parse java class file

Wrapper class that parses a given Java .class file. The method parse returns a JavaClass object on success. When an I/O error or an inconsistency occurs an appropiate exception is propagated back to the caller. The structure and the names comply, except for a few conveniences, exactly with the JVM specification 1.0. See this paper for further details about the structure of a bytecode file.

Version: $Id: ClassParser.java,v 1.3 2001/05/09 09:26:57 dahm Exp $ Author: M. Dahm

Constructor Summary
ClassParser (java.io.InputStream file, java.lang.String file_name)
Parse class from the given stream.
ClassParser (java.lang.String file_name)
Parse class from given .class file.
ClassParser (java.lang.String zip_file, java.lang.String file_name)
Parse class from given .class file in a ZIP-archive
Method Summary
JavaClass parse ()
Parse the given Java class file and return an object that represents the contained data, i.e., constants, methods, fields and commands.
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

ClassParser

public ClassParser(java.io.InputStream file, java.lang.String file_name)

ClassParser

public ClassParser(java.lang.String file_name) throws java.io.IOException

ClassParser

public ClassParser(java.lang.String zip_file, java.lang.String file_name) throws java.io.IOException

parse

public JavaClass parse() throws java.io.IOException, java.lang.ClassFormatError

Parse the given Java class file and return an object that represents the contained data, i.e., constants, methods, fields and commands. A ClassFormatError is raised, if the file is not a valid .class file. (This does not include verification of the byte code as it is performed by the java interpreter). Returns: Class object representing the parsed class file

Overview Package Class Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: INNER | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Читайте также:  Java help code 1603

☕ A parser for Java Classfiles written in rust

License

Palmr/classfile-parser

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A parser for Java Classfiles, written in Rust using nom.

Classfile Parser is available from crates.io and can be included in your Cargo enabled project like this:

[dependencies] classfile-parser = "~0.3"
extern crate classfile_parser; use classfile_parser::class_parser; fn main()  let classfile_bytes = include_bytes!("../path/to/JavaClass.class"); match class_parser(classfile_bytes)  Ok((_, class_file)) =>  println!( "version <>,<> \ const_pool(<>), \ this=const[<>], \ super=const[<>], \ interfaces(<>), \ fields(<>), \ methods(<>), \ attributes(<>), \ access()", class_file.major_version, class_file.minor_version, class_file.const_pool_size, class_file.this_class, class_file.super_class, class_file.interfaces_count, class_file.fields_count, class_file.methods_count, class_file.attributes_count, class_file.access_flags ); > Err(_) => panic!("Failed to parse"), >; >
  • Header
    • Magic const
    • Version info
    • Constant pool size
    • Constant types
      • Utf8
      • Integer
      • Float
      • Long
      • Double
      • Class
      • String
      • Fieldref
      • Methodref
      • InterfaceMethodref
      • NameAndType
      • MethodHandle
      • MethodType
      • InvokeDynamic
      • Basic attribute info block parsing
      • Known typed attributes parsing
        • Critical for JVM
          • ConstantValue
          • Code
          • StackMapTable
          • Exceptions
          • BootstrapMethods
          • InnerClasses
          • EnclosingMethod
          • Synthetic
          • Signature
          • RuntimeVisibleAnnotations
          • RuntimeInvisibleAnnotations
          • RuntimeVisibleParameterAnnotations
          • RuntimeInvisibleParameterAnnotations
          • RuntimeVisibleTypeAnnotations
          • RuntimeInvisibleTypeAnnotations
          • AnnotationDefault
          • MethodParameters
          • SourceFile
          • SourceDebugExtension
          • LineNumberTable
          • LocalVariableTable
          • LocalVariableTypeTable
          • Deprecated

          About

          ☕ A parser for Java Classfiles written in rust

          Источник

          Beyond Java

          If you want to parse a java class, it is a clever idea to fetch a java grammar and let JavaCC do the work for you. However, I didn’t find a grammar for Java 7, so I decided to write my own parser. This parser can also read Groovy source code and most of the Java 8 source code (apart from defender methods).

          Another reason to write the parser was to show how simple file and text manipulations can be. Groovy is optimized for programming these tasks (at the cost of being a little slower). The parser consists of merely 263 lines, including a couple of comments and blank lines. I guess the Java version is a lot more verbose.

          License

          Feel free to use the source code if you need it. Please note that I provide it to you on a «as-is» basis: if you use the source code, you use it at your own risk. You can download it here.

          The regular expressions

          The most important file of the project contains the regular expressions I use to extract classes, variable, methods, assignments and annotations:

          The main class

          The class definition

          This class is the definition of a single class.

          package de.beyondjava.VariableParser; import java.util.List; import java.util.regex.Matcher import java.util.regex.Pattern; import static RegularExpressions.* /** * Description of a class, including a list of its variables and methods (but ignoring the parameter lists of the methods) */ public class ClassDefinition < String packageName; String className; List variables = [] List methods = [] List modifiers=[]; List annotations=[]; /** * extract the variables and methods from the implementation */ ClassDefinition (String p_packageName, String p_classDeclaration, String p_impl) < Matcher m = p_classDeclaration =~ ANNOTATION m.each() // simplify expression by removing annotations p_classDeclaration = p_classDeclaration.replaceAll(ANNOTATION,"") List words = p_classDeclaration.split("class"); words = words.findAll className = words[-1].trim() if (words.size()>1) < modifiers = words. [3] collect > packageName=p_packageName def implementation=removeImplementationDetails(p_impl) extractVariablesAndMethods(implementation) > /** * In order to keep things simple, we remove the implementation of the methods. */ public String removeImplementationDetails(String p_theSourcecode) < // This regular expression removes everything enclosed between curly braces p_theSourcecode.replaceAll(JAVA_BLOCK_REGEXP,"\n") >private void extractVariablesAndMethods(String p_impl) < Matcher m = p_impl =~ VARIABLE_OR_METHOD_REGEXP def meths = m.findAll.collect methods = meths.collect < new MethodDefinition(it)>def vars = m.findAll.collect variables = vars.collect < new VariableDefinition(it)>> >

          package de.beyondjava.VariableParser; import static RegularExpressions.* import java.util.List; import java.util.regex.Matcher /** * This is the definition of a method (without the implementation details and without the parameter list). */ public class MethodDefinition < List visibility = [] String name String type List annotations=[] String parameters boolean isConstructor MethodDefinition(String p_method) < Matcher m = p_method =~ ANNOTATION m.each() // simplify expression by removing annotations p_method = p_method.replaceAll(ANNOTATION, «») // extract parameter list m = p_method =~ PARAMETERS m.each() // simplify expression by removing parameters p_method = p_method.replaceAll(PARAMETERS, «») String[] words = p_method.split(NON_EMPTY_SPACE.toString()) name=words[-1] if (words.size()==1 || words[-2] == «public» || words[-2] == «private» || words[-2] == «protected») < isConstructor = true if (words.length >1) < visibility=words [4] > > else < type=words[-2] if (words.length >2) < visibility=words [5] > > > >

          The description of a variable

          . is almost identical to the description of a method:

          package de.beyondjava.VariableParser; import java.util.regex.Matcher import java.util.regex.Pattern; import static RegularExpressions.* /** * This a the definition of a variable. */ class VariableDefinition < List modifiers=[]; String name; String type; List annotations=[]; String value=null; // optional /** Receives the complete variable definition source code and extracts the name, * the type and the visibility. * @param p_variable variable definition (without assignment) */ VariableDefinition(String p_variable) < Matcher m = p_variable =~ ANNOTATION m.each() // simplify expression by removing annotations p_variable = p_variable.replaceAll(ANNOTATION,"") // and assignments m = p_variable =~ ASSIGNMENT m.each() p_variable = p_variable.replaceAll(ASSIGNMENT,"") String[] words = p_variable.split(NON_EMPTY_SPACE.toString()) name=words[-1] type=words[-2] if (words.length > 2) < modifiers=words [6] > > >

          The JUnit test and example classes

          package de.beyondjava.VariableParser; import java.util.List; import de.beyondjava.Beans.Address import groovy.util.GroovyTestCase; class VariableParserTest extends GroovyTestCase < public void testParser() < SimpleClassParser parser = new SimpleClassParser() List classes = parser.parse("src/de/beyondjava/Beans") assertEquals(2, classes.size()) int vars=0 int meths=0 classes.each(println "$ contains $ variables and $ methods" vars += c.variables?.size() meths += c.methods?.size() >) assertEquals(7, vars) assertEquals(4, meths) > > package de.beyondjava.Beans; import javax.faces.bean.ManagedBean; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @ManagedBean public class Address < @Size(max=40) String street = "< lorem ipsum >«; @NotNull @Size(min=1, max=40) public String city= null; private int zipCode = 64546; /** * This is the default constructor. */ public Address() < street = "unknown"; city = "in the middle of nowhere"; zipCode = 0; >protected void initRandomly() < zipCode = (int)( System.currentTimeMillis() % 100000l); >public void initRandomly(int p_value) < zipCode = (int)( System.currentTimeMillis() % 100000l); >void increaseZipCode() < zipCode++; >> package de.beyondjava.Beans; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; public class Person

          Alternatives

          Of course, there are more professional class parsers out there. For instance, you can use the class parser and AST generator of Eclipse. Two small frameworks making Eclipse JDT easily accessible are

          Источник

Оцените статью