본문 바로가기

카테고리 없음

COM4J Intro

com4j 사용예



Download


Tutorials


참고: 64비트 환경에서는 작동하지 않은 것으로 알려져 있다


com4j is the best and the most powerful library for accessing com components. It consists of two things.

  1. A Java library that allows Java applications to seemlessly interoperate with Microsoft Component Object Model.
  2. A Java tool that imports a COM type library and generates the Java definitions of that library.

    com4j tutorial

Generate Type Definitions

Usually, the first step of using com4j is to generate Java type definitions from a COM type library. COM type libraries are often found in .ocx, .dll, .exe, and/or .tlb files. I still don't know how to locate type libraries for a given COM library other than guessing the file by using OleView.

In this tutorial, we use %WINDIR%\system32\wshom.ocx, which contains a type library for the Windows Scripting Host. This type library should be available in all the modern flavors of Windows.

To generate Java definitions from a type library, do as follows:

> java -jar tlbimp.jar -o wsh -p test.wsh %WINDIR%\system32\wshom.ocx

위의 명령을 Windows 7, 64bit, JDK 1.7 환경에서 실행할 때 아래처럼 수행하여 성공할 수 있었다

다운로드한 압축파일을 해제하면 tlbimp.jar 파일이 있는데 이것을 이용하여 콘솔에서 명령하면 많은 자바파일이 생성된다

> java -jar tlbimp.jar -o wsh -p test.wsh %WINDRI%\sysWOW64\wshom.ocx


구글 어스에서 제공하는 COM 오브젝트를 사용하기 위해서는 다음과 같이 명령하면 된다

java -jar tlbimp.jar -o ge_code -p com.brant.ge "c:\program files\google\google earth\googleearth.exe"


대신증권에서 제공하는 COM 오브젝트를 사용하는 경우(CpDib.dll, CpUtil.dll) 파일을 타겟으로 명령을 실행한다

대신증권에서 제공하는 HTS(Home Trading System)인 CYBOS를 설치하고 실행한 후에 CYBOS Plus 메뉴를 눌러서 CYBOS Plus 를 실행하면 관련 DLL 파일들이 설치되는데, CpDib.dll, CpUtil.dll, CpSysDib.dll, CpTrade.dll 파일은 COM 오브젝트로 이용자에게 제공하여 이용자가 자신의 취향에 적합한 투자시스템을 개발할 수 있도록 하고 있다.

java -jar tlbimp.jar -o ds -p test.cp "C:\DaiShin\cybosplus\CpDib.dll"

java -jar tlbimp.jar -o ds -p test.cp "C:\DaiShin\cybosplus\CpUtil.dll"


This should generate Java definitions in the test.wsh Java package and place all the files under the wsh directory.

Learn What's Generated

First, take a look at the generated ClassFactory class. This class contains a series of create*** methods that are used to create new instances of COM objects.

public abstract class ClassFactory {
    public static IFileSystem3 createFileSystemObject() {
        return COM4J.createInstance( IFileSystem3.class, "{0D43FE01-F093-11CF-8940-00A0C9054228}" );
    }
    ...
}

Calling these methods causes an instanciation of a COM object, and returns a reference to its wrapper.

tlbimp also generates one Java interface for each interface definition found in a type library. Typically they look like the following:

@IID("{2A0B9D10-4B87-11D3-A97A-00104B365C9F}")
public interface IFileSystem3 extends IFileSystem {
    @VTID(32)
    ITextStream getStandardStream(
        StandardStreamTypes standardStreamType,
        boolean unicode);

    @VTID(33)
    java.lang.String getFileVersion(
        java.lang.String fileName);
}

When you are just trying to use definitions generated from tlbimp, you can ignore all those annotations. Those are used to configure the com4j runtime to do the bridging correctly. These interfaces are implemented by the com4j COM object wrapper, and calling a method on this interface causes the runtime to call the corresponding COM method.

Additionally, tlbimp generates enumerations when a type library defines them.

public enum StandardStreamTypes {
    StdIn, // 0
    StdOut, // 1
    StdErr, // 2
}

Using Generated Code

Using the generated code is simple. The following code illustrates how you can use the IFileSystem3.getFileVersion method to obtain the version string of a file.

위의 콘솔명령으로 생성된 파일을 테스트하는 코드

Eclipse 에서 프로젝트를 생성하고 com4j.jar 파일을 라이브러리로 프로젝트에 추가한다.

그리고 위에서 생성된 모든 파일들을 프로젝트로 임포트한 후에 아래와 같은 Main 클래스를 작성하여 실행해보면 작동여부를 확인할 수 있다

이때 ClassFactory 라는 클래스를 이용하여 관련된 COM 오브젝트를 생성하고 COM 오브젝트가 포함한 메소드를 호출하여 작업을 수행하면 된다

package test.wsh;

public class Main { 

	public static void main(String[] args) {
		IFileSystem3 fs = ClassFactory.createFileSystemObject();
		String[] files = new String[]{"C:/Apache24/bin/ab.exe"};
	    for( String file : files )
	      System.out.println("파일="+fs.getFileVersion(file));
	}
}


대신증권에서 제공하는 주식관련 데이터(시세데이타 인터페이스)를 프로그램을 개발하려면

대신증권 사이트에서 CYBOS Plus 도움말 파일을 다운로드하여 COM 오브젝트의 레퍼런스를 참고하면 함수를 사용하는데 도움이 될 것이다

cybosplushelp.zip