如何使用javaparser获取类级变量声明? [英] How to get class level variable declarations using javaparser ?

查看:207
本文介绍了如何使用javaparser获取类级变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想只获得类级变量声明。如何使用javaparser获取声明?

I want to get only the class level variable declarations. How can i get the declarations using javaparser?

public class Login {

    private Keyword browser;
    private String pageTitle = "Login";
}

使用javaparser必须获取变量browser的详细信息,如类型浏览器是KeyWord

Using javaparser have to get the details of variable "browser" like the type of browser is "KeyWord"

推荐答案

我不太清楚我理解你的问题 - 你想要得到所有的现场成员吗?类?如果是这样,你可以这样做:

Not quite sure i understood your question - do you want to get all the field-members of a class? if so you can do it like this:

CompilationUnit cu = JavaParser.parse(javaFile);
for (TypeDeclaration typeDec : cu.getTypes()) {
    List<BodyDeclaration> members = typeDec.getMembers();
    if(members != null) {
        for (BodyDeclaration member : members) {
        //Check just members that are FieldDeclarations
        FieldDeclaration field = (FieldDeclaration) member;
        //Print the field's class typr
        System.out.println(field.getType());
        //Print the field's name 
        System.out.println(field.getVariables().get(0).getId().getName());
        //Print the field's init value, if not null
        Object initValue = field.getVariables().get(0).getInit();
        if(initValue != null) {
             System.out.println(field.getVariables().get(0).getInit().toString());
        }  
    }
}

此代码示例将打印在你的情况:
关键字
浏览器
字符串
pageTitle
登录

This code example will print in your case: Keyword browser String pageTitle "Login"

我希望这是真的你的问题......如果没有,请发表评论。

I hope this was really your question... if not, please comment.

这篇关于如何使用javaparser获取类级变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆