码迷,mamicode.com
首页 > 编程语言 > 详细

java——JavaPoet

时间:2019-01-20 13:59:24      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:int   addm   ref   oncreate   creat   activity   world   details   div   

    public static void main(String [] args){
        ClassName activity = ClassName.get("android.app", "Activity");

        TypeSpec.Builder mainActivityBuilder = TypeSpec.classBuilder("MainActivity")
                .addModifiers(Modifier.PUBLIC)
                .superclass(activity);

        ClassName override = ClassName.get("java.lang", "Override");

        ClassName bundle = ClassName.get("android.os", "Bundle");

        ClassName nullable = ClassName.get("android.support.annotation", "Nullable");

        ParameterSpec savedInstanceState = ParameterSpec.builder(bundle, "savedInstanceState")
                .addAnnotation(nullable)
                .build();

        MethodSpec onCreate = MethodSpec.methodBuilder("onCreate")
                .addAnnotation(override)
                .addModifiers(Modifier.PROTECTED)
                .addParameter(savedInstanceState)
                .addStatement("super.onCreate(savedInstanceState)")
                .addStatement("setContentView(R.layout.activity_main)")
                .build();

        MethodSpec hello = MethodSpec.methodBuilder("hello")
                .addModifiers(Modifier.PUBLIC)
                .addStatement("System.out.println(\"hello world\")")
                .build();

        TypeSpec mainActivity = mainActivityBuilder.addMethod(onCreate)
                .addMethod(hello)
                .build();

        JavaFile file = JavaFile.builder("com.test", mainActivity).build();

        File f = null;
        try {
            file.writeTo(System.out);
            f = new File("C:\\JavaWorkspace\\annotationTest\\poetTest");
            file.writeTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

很神奇,还不太会用,只能照葫芦画瓢

https://blog.csdn.net/l540675759/article/details/82931785

java——JavaPoet

标签:int   addm   ref   oncreate   creat   activity   world   details   div   

原文地址:https://www.cnblogs.com/gaoquanquan/p/10294401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!