6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Eclipse】Javaソースコードを解析するプラグインを自作し、Eclipseに導入するまでの流れ

Last updated at Posted at 2016-06-26

Javaソースコードを解析するプラグインを自作し、Eclipseに導入するまでの流れを書き残す。

①PDE(Plug-in Development Environment)をインストールして再起動する。
②プラグインプロジェクトを作成する(テンプレートはHello, World Command)。
③依存プラグインにorg.eclipse.core.runtime、org.eclipse.jdt.coreを追加する。
④SampleHandler.javaを以下のように書き換える。

SampleHandler.java

package aaaproject.handlers;

import java.util.Optional;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.ui.handlers.HandlerUtil;

public class SampleHandler extends AbstractHandler {
    public SampleHandler() {
    }

    public Object execute(ExecutionEvent event) throws ExecutionException {
        ICompilationUnit source = Optional.of(event)
            .map(HandlerUtil::getActiveEditorInput)
            .map(input -> (ICompilationUnit)input.getAdapter(IJavaElement.class))
            .orElse(null);
        
        if (source == null) {
            return null;
        }
        
        ASTParser parser = ASTParser.newParser(AST.JLS8);
        parser.setSource(source);
        CompilationUnit root = (CompilationUnit)parser.createAST(null);
        
        // ここで解析を行う
        
        return null;
    }
}

⑤解析の処理を記述する。解析にはASTVisitorクラスとCompilationUnit#accept(ASTVisitor)を使用する。
⑥解析の処理を記述し終えたら、plugin.xmlを開く。
⑦Overviewの右下にExportingというのがあるので、ここからエクスポートしてJARファイルを作成する。
⑧作成したJARファイルを、Eclipseのpluginsフォルダに格納する。

Eclipseを起動すると、上部メニューにSample Menuというのが追加され、その中のSample Commandを選択すると解析が行われる。Javaソースファイルをエディタで開いていないと何も起きないので注意(source == nullのチェックに引っかかって途中で処理が終了する)。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?