简体   繁体   English

如何计算出现在Android类中的每种变量类型的数量? 例如int,string等

[英]How can I count the number each variable type, appears in an Android class? e.g. int, string etc

I've created a small Android application which reads in, a particular Android class (.java). 我已经创建了一个小的Android应用程序,它可以读取特定的Android类(.java)。

I'd like to (but currently don't know how): 我想(但目前不知道如何):

  • Count the number each variable type is globally declared (as it is on the page, not during or after run-time etc.) eg 计算每个变量类型被全局声明的数量 (因为它在页面上,而不是在运行时或之后),例如

5 regular ints , 3 regular strings , 1 regular drawables , 2 ArrayList of ints 5个常规整数3个常规字符串1个常规可绘制对象2个ArrayList

  • Count the number each variable type is locally declared, in each function (as it is on the page, not during or after run-time etc.) eg 计算每个函数中每个变量类型在本地声明的数量 (如在页面上一样,而不是在运行时或运行后等),例如

Function A: 2 regular ints , 1 regular strings 函数A: 2个常规整数1个常规字符串

Function B: 3 regular drawables , 4 ArrayList of ints 函数B: 3个常规可绘制对象4个ArrayList int

  • Count the number of subroutines and functions, within the class (as it is on the page, not during or after run-time etc.) 计算类中的子例程和函数的数量 (因为它在页面上,而不是在运行时或运行后等)

So far I've figured out the below, but due to the programmatic nature it doesn't work correctly: 到目前为止,我已经弄清楚了以下内容,但是由于程序性质,它无法正常工作:

        int numberofArrayLists = Collections.frequency(androidClass, "ArrayList<String>");
        int numberofIntLists = Collections.frequency(androidClass, "ArrayList<Int>");
        int numberofBooleanLists = Collections.frequency(androidClass, "ArrayList<Boolean>");

My code: 我的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        ArrayList<String> androidClass =  readAndroidClass("/sdcard/MainActivity.java");
    } catch (IOException e) {
        e.printStackTrace();
    }
}


public ArrayList<String> readAndroidClass(String classLocationString) throws IOException {
    ArrayList<String> androidClass = new ArrayList<String>();
    FileInputStream is;
    BufferedReader reader;
    final File classLocation = new File(classLocationString);

    if (classLocation.exists()) {
        is = new FileInputStream(classLocation);
        reader = new BufferedReader(new InputStreamReader(is));
        String line = reader.readLine();
        while(line != null){
            androidClass.add(reader.readLine());
        }
    }

    return androidClass;
}

Example of an Android Java class to attempt the above: 尝试上述操作的Android Java类示例:

public class MainActivity extends ListActivity {
    private PackageManager packageManager = null;
    private List<ApplicationInfo> applist = null;
    private ApplicationAdapter listadaptor = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        packageManager = getPackageManager();

        new LoadApplications().execute();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);

        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        return false;
    }

    private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
        ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
        for (ApplicationInfo info : list) {
            try {
                if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
                    applist.add(info);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return applist;
    }

    private class LoadApplications extends AsyncTask<Void, Void, Void> {
        private ProgressDialog progress = null;

        @Override
        protected Void doInBackground(Void... params) {
            applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
            listadaptor = new ApplicationAdapter(MainActivity.this,
                    R.layout.snippet_list_row, applist);

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Void result) {
            setListAdapter(listadaptor);
            progress.dismiss();
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            progress = ProgressDialog.show(MainActivity.this, null,
                    "Loading application info...");
            super.onPreExecute();
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
    }
}

The question involves lot of code to write. 这个问题涉及许多要编写的代码。 So I am giving you an idea about how to move ahead. 所以我给你一个关于如何前进的想法。 You can use this idea, customize it and modify it to make it better. 您可以使用此想法,对其进行自定义并对其进行修改以使其更好。 Do let me know, if you need further help 如果您需要进一步的帮助,请告诉我

For counting variables at a class level: 在类级别对变量进行计数:

Create a skeleton for declaration statements: 为声明语句创建框架:

AccessMode OtherQualifier DataType VariableName EndMarker AccessMode OtherQualifier数据类型VariableName EndMarker

where    
    AccessMode       =  { private, public, protected }    
    OtherQualifier   =  { static }    
    DataType         =  { int, char, string, boolean ..}    
    VariableName     =  { anything }    
    EndMarker        =  { ; , }

Write a function to detect whether a line is variable declaration or not 编写函数以检测行是否为变量声明

private boolean isLineVariableDeclaration(String line)
{
    this.hasAccessMode(line)
    // call other functions too ..
}

private bool hasAccessMode(String line)
{
    String access = line.Split(" ")[0].toLowerCase();

    // Check if AccessMode list has "access"
    // return true if it exists
}

private bool hasOtherQualifier(String line)
{
    String qualifier = line.Split(" ")[1].toLowerCase();

    // Check if OtherQualifier list has "qualifier"
    // return true if it exists
}

private bool hasDataType(String line)
{
    String dataType = line.Split(" ")[2].toLowerCase();

    // Check if DataType list has "dataType"
    // return true if it exists
}

private bool hasEndMarker(String line)
{
    String endMarker = line.Split(" ")[3].toLowerCase();

    // Statement looks like
    // private static int someVar;
    if(endMarker.Equals(";"))
    {
        // since this is line end
       // return true;
    }
    // Statement looks like
    // private static int someVar, someOtherVar;
    else if(endMarker.Equals(","))
    {
        // this means there are more variables so such type
        // do more to collect them
    }
} 

For counting variables inside a function: 在函数内部对变量进行计数:

Create a skeleton for declaration statements: 为声明语句创建框架:

OtherQualifier DataType VariableName EndMarker OtherQualifier数据类型变量名EndMarker

where      
    OtherQualifier   =  { static }    
    DataType         =  { int, char, string, boolean ..}    
    VariableName     =  { anything }    
    EndMarker        =  { ; , }

Using similar approach, write function here. 使用类似的方法,在此处编写函数。 For finding presence of "{" and "}" ie to detect function starting and closing do one thing: 为了找到“ {”和“}”的存在,即检测功能的启动和关闭,请做一件事:

  • Set a int bracesCounter = 0; 设置一个int bracesCounter = 0;
  • Whenever you encounter a { , increase bracesCounter 每当遇到{ ,增加大bracesCounter
  • Whenever you encounter a '}', decrease bracesCounter 每当遇到“}”时,请减少大bracesCounter
  • The moment your bracesCounter is zero again, you are out of function scope bracesCounter再次为零时,您就超出了功能范围

For counting number of if statements: 要计算if语句的数量:

Create a skeleton for statements: 为语句创建框架:

IF_KEYWORD LEFT_FUNCTION_BRACKET EXPRESSION RIGHT_FUNCTION_BRACKET OTHER IF_KEYWORD LEFT_FUNCTION_BRACKET EXPRESSION RIGHT_FUNCTION_BRACKET OTHER

where    
   IF_KEYWORD                    = { if }   
   LEFT_FUNCTION_BRACKET         = { ( }    
   EXPRESSION                    = { WITHOUT_OPERATOR, WITH_OPERATOR }       
   WITHOUT_OPERATOR              = { SIMPLE_OPERAND, OPERAND_WITH_FUNC }      
   SIMPLE_OPERAND                = { OPERAND }    
   OPERAND_WITH_FUNC             = { OPERAND.FUNC(), !OPERAND.FUNC() }     
   WITH_OPERATOR                 = { SIMPLE_OPERAND_WITH_OPERATOR,  OPERAND_WITH_FUNC_OPERATOR }   
   SIMPLE_OPERAND_WITH_OPERATOR  = { LEFT_OPERAND OPERATOR RIGHT_OPERAND }
   OPERAND_WITH_FUNC_OPERATOR    = { OPERAND_WITH_FUNC OPERATOR OPERAND_WITH_FUNC  }    
   LEFT_OPERAND                  = { OPERAND }   
   RIGHT_OPERAND                 = { OPERAND }    
   OPERATOR                      = { !=, ==, >, <, >=, <= }    
   OTHER                         = { RIGHT_CURLY_BRACES, NEW_LINE} 
   RIGHT_CURLY_BRACES            = { { } 
   NEW_LINE                      = { \n } 
so on and so forth..

However, above may seen tedious to you, if your requirement is just to count if's (or while's). 但是,如果您的要求仅仅是计算if(或while)的数量,那么上面的内容可能对您来说很繁琐。 So, instead, you can do this 因此,您可以执行此操作

  • On any line if you encounter if check if it followed by ( 在任何行上,如果遇到if请检查是否后面跟着(
  • Set brackets = 1 设置括号 = 1
  • Now whenever you encounter ( increase brackets by 1 and whenever you encounter whenever you encounter ) decrease brackets by 1. 现在,每当您遇到(方括号增加1,并且每当您遇到相遇时)方括号减少1。
  • When brackets become 0 , if condition statement is parsed successfully 方括号变为0 ,如果条件语句成功解析
  • Please note: Keep on reading lines and lines, until brackets become zero 请注意:继续阅读线条和线条,直到括号变为零
  • Now, when brackets is 0 see if it is followed by { 现在,当方括号为0请查看其后是否跟{
  • If yes, again set brackets = 1 Now whenever you encounter { increase brackets by 1 and whenever you encounter whenever you encounter } decrease brackets by 1. 如果是,请再次设置方括号= 1现在,每当遇到{括号增加1,并且遇到}括号减小1。
  • When brackets become 0 , if statement is parsed successfully 方括号变为0 ,如果语句成功解析

You are done ! 大功告成!

PS Modify the algorithm above to suit your needs PS修改以上算法以满足您的需求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以编程方式动态创建所有Android ui组件的列表?例如TextView,ImageView等 - How can I dynamically create a list of all Android ui components programmatically? e.g. TextView, ImageView etc 如何为类型参数的类调用.class? 例如清单 <String> 。类 - How to call .class for a class with type parameter? E.g. List<String>.class 在 Java 正则表达式中,如何获取字符类(例如 [az])以匹配 - 减号? - In a java regex, how can I get a character class e.g. [a-z] to match a - minus sign? 如何从另一个类访问对象(例如ArrayList)? - How can I access an object (e.g. ArrayList) from another class? 如何检查for循环中当前索引处的字符是否为特定字符(例如字母A,数字2等)? - How to check if character at current index in for loop is a specific character (e.g. the letter A, the number 2, etc)? 为什么Java equals(Object O)方法没有可将特定对象类型(例如String,Integer等)作为输入的变量? - Why does the Java equals(Object O) method not have a variant which can take a specific object type (e.g. String, Integer, etc) as input? 如果重写方法的返回类型是原始的(例如double),我们可以更改重写方法的返回类型(例如int,char)吗? - if overridden method's return type is primitive (e.g. double) ,can we change return type of overriding method (e.g. int ,char)? 如何在Java中查看内置类的源代码(例如BigInteger等)? - How do I view source code of built-in classes in Java (e.g. BigInteger etc.)? 可以使用反射来获得具体的实现类型(例如Class <? extends MyInterface> )? - Can reflection be used to get a concrete implementing type (e.g. Class<? extends MyInterface>)? 如何从非常重的文件中读取字节? 然后将其存储在字符串中,例如.pdf .zip .xlsx文件 - How can i read bytes from a very heavy file? then store store them in a String e.g. .pdf .zip .xlsx files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM