`

Use CodeMoel Generate Java Source Code

 
阅读更多
package samples;

// Example: CodeFactory.java
import java.io.File;

import org.apache.log4j.Logger;

import com.sun.codemodel.JBlock;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JDocComment;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;

/** * * @author naman */
public class CodeFactory {
	private Logger logger = Logger.getLogger(CodeFactory.class);

	// Method to get JType based on any String Value
	public JType getTypeDetailsForCodeModel(JCodeModel jCodeModel, String type) {
		if (type.equals("Unsigned32")) {
			return jCodeModel.LONG;
		} else if (type.equals("Unsigned64")) {
			return jCodeModel.LONG;
		} else if (type.equals("Integer32")) {
			return jCodeModel.INT;
		} else if (type.equals("Integer64")) {
			return jCodeModel.LONG;
		} else if (type.equals("Enumerated")) {
			return jCodeModel.INT;
		} else if (type.equals("Float32")) {
			return jCodeModel.FLOAT;
		} else if (type.equals("Float64")) {
			return jCodeModel.DOUBLE;
		} else {
			return null;
		}
	}

	// Function to generate CodeModel Class
	public void writeCodeModel(String factroyPackage) {
		try {
			/* Creating java code model classes */
			JCodeModel jCodeModel = new JCodeModel();

			/* Adding packages here */
			JPackage jp = jCodeModel._package(factroyPackage);
			/* Giving Class Name to Generate */
			JDefinedClass jc = jp._class("GeneratedFactory");
			/* Adding annotation for the Class */
			// jc.annotate(com.myannotation.AnyXYZ.class);
			/* Adding class level coment */
			JDocComment jDocComment = jc.javadoc();
			jDocComment.add("Class Level Java Docs");
			/*
			 * Adding method to the Class which is public static and returns
			 * com.somclass.AnyXYZ.class
			 */
			String mehtodName = "myFirstMehtod";
			JMethod jmCreate =
			    jc.method(JMod.PUBLIC | JMod.STATIC,Integer.class,"create" + mehtodName);
			/* Addign java doc for method */
			jmCreate.javadoc().add("Method Level Java Docs");
			/* Adding method body */
			JBlock jBlock = jmCreate.body();
			/* Defining method parameter */
			JType jt = getTypeDetailsForCodeModel(jCodeModel,"Unsigned32");
			if (jt != null) {
				jmCreate.param(jt,"data");
			} else {
				jmCreate.param(java.lang.String.class,"data");
			}
			/* Defining some class Variable in mthod body */
			JClass jClassavpImpl = jCodeModel.ref("org.isunday.tools.CodeGenerator");// .ref(Integer.class);
			JVar jvarAvpImpl = jBlock.decl(jClassavpImpl,"varName");
			jvarAvpImpl.init(JExpr._new(jClassavpImpl));
			/* Adding some direct statement */
			jBlock.directStatement("varName.setCode(100);");
			/* returning varibalbe */
			jBlock._return(jvarAvpImpl);
			/* Building class at given location */
			File file = new File("./target/classes");
			file.mkdirs();
			jCodeModel.build(file);
		} catch (Exception ex) {
			logger.debug("Other Exception which in not catched:" + ex);
			ex.printStackTrace();
		}
	}

	public static void main(String[] agrs) {
		new CodeFactory().writeCodeModel("aito.java");
	}
}


生成文件内容:
Generated Class: GeneratedFactory.java

package com.test;

import com.myannotation.AnyXYZ;
import com.somclass.AnyXYZ;

/**
 * Class Level Java Docs
 * 
 */
@com.myannotation.AnyXYZ
public class GeneratedFactory {

    /**
     * Method Level Java Docs
    * 
    */
    public static com.somclass.AnyXYZ myFirstMehtod(long data) {
        com.somclass.AnyXYZ varName = new com.somclass.AnyXYZ();
        varName.setCode(100);
        return varName;
    }
}
参考资料:
http://namanmehta.blogspot.tw/2010/01/use-codemodel-to-generate-java-source.html
分享到:
评论

相关推荐

    jad 最新版java反编译

    -nocode - don't generate the source code for methods -noctor - suppress the empty constructors -nodos - turn off check for class files written in DOS mode -nofd - don't disambiguate fields with ...

    《Java Design Patterns》高清完整PDF版

    There is no need to know advanced concepts of Java to use this book. Each of the concepts is connected with a real world example and a computer world example. The book uses Eclipse IDE to generate ...

    TC环境精简压缩软件

    AutoFlowchart, the Professional sourcecode flowcharting tool. AutoFlowchart is a excellent tool to generate flowchart from sourcecode.Its flowchart can expand and shrink. and you can pre-define ...

    C语言流程生成器

    AutoFlowchart, the Professional sourcecode flowcharting tool. AutoFlowchart is a excellent tool to generate flowchart from sourcecode.Its flowchart can expand and shrink. and you can pre-define ...

    androidjava源码-AutoHttp:Autogenerate`HTTPsourcecode`forAndroidandJava.自动

    source code 。自动生成http java源代码。 执照 Copyright 2014 Google, Inc. Copyright 2015 Square, Inc. Copyright 2016 BiaoWu Licensed under the Apache License, Version 2.0 (the "License"); you may not ...

    java反编译工具FrontEnd和jad

    -nocode - don't generate the source code for methods -noconv - don't convert Java identifiers (default: convert) -noctor - suppress the empty constructors -nodos - do not check for class files ...

    Java反编译软件JAD1

    -nocode - don't generate the source code for methods -noconv - don't convert Java identifiers (default: do) -noctor - suppress the empty constructors -noinner - turn off the support of inner ...

    jclazz-1.2.2

    * Decompiler can be used to reproduce Java source code from compiled Java class file. It uses debug information to produce Java code which is nearly the same as original source file. Nevertheless...

    Java Design Patterns(Apress,2015)

    Learn how to implement design patterns in Java: each pattern in Java Design Patterns is a complete implementation and the output is generated using Eclipse, making the code accessible to all....

    《Java Design Patterns》高清完整英文PDF版

    Learn how to implement design patterns in Java: each pattern in Java Design Patterns is a complete implementation and the output is generated using Eclipse, making the code accessible to all....

    demo code for pictohex

    this is source code which demo how to convert a bmp file to digt or hex code and the hex code is automatic generate by click the icon after you use open to open a bmp file

    jad.exe+readme.txt

    -nocode - don't generate the source code for methods -noconv - don't convert Java identifiers (default: do) -noctor - suppress the empty constructors -noinner - turn off the support of inner ...

    java反编译工具jad 1.5.8g(可以反编译jdk1.5,1.6)

    -nl - split strings on newline character (default: off) -nocast - don't generate auxiliary casts -nocode - don't generate the source code for methods -noconv - don't convert Java ...

    Microsoft CDIMAGE v2.52

    -c use ANSI filenames versus OEM filenames from source -j1 encode Joliet Unicode filenames AND generate DOS-compatible 8.3 filenames in the ISO-9660 name space (can be read by either Joliet ...

    C流程图生成器

    sourcecode.Its flowchart can expand and shrink. and you can pre-define the the width , height,Horizontal spacing and vertical spacing. Move and zoom is also very easy. It can export the flow...

    OpenAPI v3.0.2

    The OpenAPI Specification (OAS) defines a standard, language-agnostic ... code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases.

    Pro Radar Builder (Source Included) 3.0.1

    Since this is the source included version you have access to all the source code you need.. For 2D Radars please see: 2D Radar Builder For 3D Radars please see: 3D Radar Builder Simple AI (just ...

    Java邮件开发Fundamentals of the JavaMail API

    Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link ...

    Araxis Merge Professional 2012.4162 (x86/x64).part1

    Use it to compare and merge source code, web pages, XML and other text files with native application performance. Directly open and compare the text from Microsoft Office (Word and Excel), ...

    Araxis Merge Professional 2012.4162 (x86/x64).part2

    Use it to compare and merge source code, web pages, XML and other text files with native application performance. Directly open and compare the text from Microsoft Office (Word and Excel), ...

Global site tag (gtag.js) - Google Analytics