如何在 Android 应用程序中 运行 Java jdt AST

How to run Java jdt AST in Android Application

我正在 android 应用程序中创建一个项目。我已经在 java eclipse 环境中将 java jdt ast 作为独立应用程序实现,并且我在控制台输出上得到了我需要的东西。现在我想 运行 将该代码添加到我的 android 应用程序项目中。但是当我启动应用程序时,在 android 的 textView 中设置所有输出时,不幸的是它停止了,我不知道为什么...... 有人知道为什么会这样吗? 感谢您的帮助。

package com.example.uiui;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{
static TextView tv1;

 private String filename = "MySampleFile.java";
 private static String filepath = "/MyFileStorage";
 File myExternalFile = new File(Environment.getExternalStorageDirectory(),filepath );

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv1=(TextView)findViewById(R.id.txt1); 
    tv1.setMovementMethod(new ScrollingMovementMethod());

    Button readFromExternalStorage = 
               (Button) findViewById(R.id.getExternalStorage);
              readFromExternalStorage.setOnClickListener(this);

              //check if external storage is available and not read only  
              if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  

              } 
              else {
               myExternalFile = new File(getExternalFilesDir(filepath), filename);
              }

}

@Override
public void onClick(View v) {

     // EditText myInputText = (EditText) findViewById(R.id.myInputText);
      TextView responseText = (TextView) findViewById(R.id.responseText);
      String myData = "";
      switch (v.getId()) {
      case R.id.getExternalStorage:
           try {
           FileInputStream fis = new FileInputStream(myExternalFile);
           DataInputStream in = new DataInputStream(fis);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
             myData = myData + strLine;
            }
            in.close();
           } catch (IOException e) {
           e.printStackTrace();
           }
        //   myInputText.setText(myData);
           responseText
           .setText("MySampleFile.txt data retrieved from Internal Storage...");

           parse(myData);

           break;

      }

}



public void parse(String str) {

    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(str.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setResolveBindings(true);

    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {

        Set names = new HashSet();

    public boolean visit(VariableDeclarationFragment node) {
            SimpleName name = node.getName();
            this.names.add(name.getIdentifier());
            tv1.setText(tv1.getText()+"Declaration of '" + name + "' at line"+cu.getLineNumber(name.getStartPosition())+"\n");


            return false; // do not continue 
        }


    public boolean visit(SimpleName node) {
        if (this.names.contains(node.getIdentifier())) {
            tv1.setText(tv1.getText()+"Usage of '" + node + "' at line "+ cu.getLineNumber(node.getStartPosition())+"\n");
        }
        return true;
    }           


public boolean visit(MethodInvocation node) {
System.out.println("Method Name: " + node.getName()+"\n");

 Expression expression = node.getExpression();
      if (expression != null) {
          tv1.setText(tv1.getText()+"Expression: " + expression.toString()+"\n");

                        ITypeBinding typeBinding = expression.resolveTypeBinding();

      if (typeBinding != null) {
          tv1.setText(tv1.getText()+"Type: " + typeBinding.getName());
                        }
                    }
           IMethodBinding binding = node.resolveMethodBinding();
      if (binding != null) {
           ITypeBinding type = binding.getDeclaringClass();
      if (type != null) {
          tv1.setText(tv1.getText()+"Decl: " + type.getName());
                        }
                    }

                    return true;
                }
            });
        }



private static boolean isExternalStorageReadOnly() {  
      String extStorageState = Environment.getExternalStorageState();  
      if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
       return true;  
      }  
      return false;  
     }  

     private static boolean isExternalStorageAvailable() {  
      String extStorageState = Environment.getExternalStorageState();  
      if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
       return true;  
      }  
      return false;  
     }  


}

代码没有显示错误,但应用程序无法运行...

现在我想到了另一个问题:我们真的可以将 java jdt ast 用作 android 应用程序吗?导入了相同的库,但代码在用作 java 应用程序项目时工作正常..

无论如何,这里是来自 logCat.

的堆栈跟踪
09-01 03:38:05.780: E/AndroidRuntime(21566): FATAL EXCEPTION: main
09-01 03:38:05.780: E/AndroidRuntime(21566): java.lang.NoClassDefFoundError:  org.eclipse.jdt.core.dom.ASTParser
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.example.uiui.MainActivity.parse(MainActivity.java:98)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.example.uiui.MainActivity.onClick(MainActivity.java:86)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.view.View.performClick(View.java:4475)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.view.View$PerformClick.run(View.java:18786)  
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.os.Handler.handleCallback(Handler.java:730)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.os.Handler.dispatchMessage(Handler.java:92)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.os.Looper.loop(Looper.java:176)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at android.app.ActivityThread.main(ActivityThread.java:5419)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at java.lang.reflect.Method.invokeNative(Native Method)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at java.lang.reflect.Method.invoke(Method.java:525)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
09-01 03:38:05.780: E/AndroidRuntime(21566):    at dalvik.system.NativeStart.main(Native Method)

这是我的资源布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.uiui.MainActivity" >
 <TextView
   android:id="@+id/txt1"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentLeft="true"
   android:layout_alignParentTop="true"
   android:layout_marginLeft="0dp"
   android:layout_marginTop="10dp"
   android:maxLines="200"
   android:scrollbars="vertical"
   android:text="TextView" />

   <Button
   android:id="@+id/getExternalStorage"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/txt1"
   android:layout_alignParentBottom="true"
   android:layout_marginBottom="18dp"
   android:text="Display from External Storage" />

   <EditText
   android:id="@+id/myInputText"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_above="@+id/getExternalStorage"
   android:layout_alignLeft="@+id/getExternalStorage"
   android:layout_marginBottom="75dp"
   android:ems="10"
   android:gravity="top|left"
   android:inputType="textMultiLine"
   android:lines="5"
   android:minLines="3" >
   <requestFocus />
  </EditText>

   <TextView
   android:id="@+id/responseText"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignLeft="@+id/txt1"
   android:layout_below="@+id/txt1"
   android:layout_marginTop="18dp"
   android:maxLines="200"
   android:scrollbars="vertical"
   android:text=" ad"
   android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

最后 manifest.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uiui"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

您没有指明 ParseFilesInDir() 中的哪一行是您崩溃的地方。然而,这一行在 Android:

中是完全错误的
File dirs = new File(".");

因此,首先,您需要决定将文件复制到 Android 设备的位置。您的 Android 设备不是您的开发 PC,因此该 Android 设备上没有 Java 源代码,除非您将其复制到那里。

然后,给定文件放置的位置,您需要调整 ParseFilesInDir() 以匹配。

关于放置文件的两个主要选项是 internal storage and external storage。如果您正在复制到外部存储,通常更容易将文件复制到设备上。