기본 패키지에서 클래스를 가져 오는 방법
중복 가능성 : 기본 패키지의 자바 클래스에 액세스하는 방법은 무엇입니까?
Eclipse 3.5를 사용하고 있으며 기본 패키지와 함께 일부 패키지 구조로 프로젝트를 만들었습니다. 나는 기본 패키지에서 하나 개의 클래스가 - Calculations.java을 나는 (예를 들어있는 패키지의 하나에 해당 클래스의 사용을 만들고 싶어 com.company.calc
). 기본 패키지에있는 클래스를 사용하려고하면 컴파일러 오류가 발생합니다. 기본 패키지의 클래스를 인식 할 수 없습니다. 문제는 어디입니까?
Calculations.java-소스 코드
public class Calculations {
native public int Calculate(int contextId);
native public double GetProgress(int contextId);
static {
System.loadLibrary("Calc");
}
}
다른 패키지에 수업을 넣을 수 없습니다. 이 클래스에는 Delphi에서 구현되는 몇 가지 기본 메서드가 있습니다. 해당 클래스를 폴더에 넣으면 피하고 싶은 DLL을 변경해야합니다 (정말로 할 수 없습니다). 그래서 기본 패키지에 수업을 넣었습니다.
로부터 Java 언어 사양 :
이름이 지정되지 않은 패키지에서 유형을 가져 오는 것은 컴파일 시간 오류입니다.
리플렉션 또는 다른 간접적 인 방법을 통해 클래스에 액세스해야합니다.
기본 패키지의 클래스는 패키지의 클래스에서 가져올 수 없습니다. 이것이 기본 패키지를 사용해서는 안되는 이유입니다.
문제에 대한 해결 방법이 있습니다. 그것을 달성하기 위해 반사를 사용할 수 있습니다.
먼저 대상 클래스에 대한 인터페이스 를 만듭니다Calculatons
.
package mypackage;
public interface CalculationsInterface {
int Calculate(int contextId);
double GetProgress(int contextId);
}
다음으로 대상 클래스 가 해당 인터페이스를 구현 하도록합니다 .
public class Calculations implements mypackage.CalculationsInterface {
@Override
native public int Calculate(int contextId);
@Override
native public double GetProgress(int contextId);
static {
System.loadLibrary("Calc");
}
}
마지막으로 리플렉션 을 사용하여 Calculations
클래스 의 인스턴스를 만들고 이를 유형의 변수에 할당합니다 CalculationsInterface
.
Class<?> calcClass = Class.forName("Calculations");
CalculationsInterface api = (CalculationsInterface)calcClass.newInstance();
// Use it
double res = api.GetProgress(10);
이 제안을 드릴 수 있습니다. 제 C 및 C ++ 프로그래밍 경험에서 아는 한, 같은 종류의 문제가 발생했을 때 ".C"파일의 이름을 변경하여 dll 작성 구조를 변경하여 해결했습니다. JNI 네이티브 기능을 구현 한 함수입니다. 예를 들어, "com.mypackage"패키지에 프로그램을 추가하려면 ".C"파일의 함수 / 메소드를 구현하는 JNI의 프로토 타입을 다음과 같이 변경합니다.
JNIEXPORT jint JNICALL
Java_com_mypackage_Calculations_Calculate(JNIEnv *env, jobject obj, jint contextId)
{
//code goes here
}
JNIEXPORT jdouble JNICALL
Java_com_mypackage_Calculations_GetProgress(JNIEnv *env, jobject obj, jint contextId)
{
//code goes here
}
Since I am new to delphi, I can not guarantee you but will say this finally, (I learned few things after googling about Delphi and JNI): Ask those people (If you are not the one) who provided the Delphi implementation of the native code to change the function names to something like this:
function Java_com_mypackage_Calculations_Calculate(PEnv: PJNIEnv; Obj: JObject; contextId: JInt):JInt; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
//Any variables you might be interested in
begin
//Some code goes here
end;
function Java_com_mypackage_Calculations_GetProgress(PEnv: PJNIEnv; Obj: JObject; contextId: JInt):JDouble; {$IFDEF WIN32} stdcall; {$ENDIF} {$IFDEF LINUX} cdecl; {$ENDIF}
var
//Any variables you might be interested in
begin
//Some code goes here
end;
But, A final advice: Although you (If you are the delphi programmer) or them will change the prototypes of these functions and recompile the dll file, once the dll file is compiled, you will not be able to change the package name of your "Java" file again & again. Because, this will again require you or them to change the prototypes of the functions in delphi with changed prefixes (e.g. JAVA_yourpackage_with_underscores_for_inner_packages_JavaFileName_MethodName)
I think this solves the problem. Thanks and regards, Harshal Malshe
From some where I found below :-
In fact, you can.
Using reflections API you can access any class so far. At least I was able to :)
Class fooClass = Class.forName("FooBar");
Method fooMethod =
fooClass.getMethod("fooMethod", new Class[] { String.class });
String fooReturned =
(String) fooMethod.invoke(fooClass.newInstance(), "I did it");
Unfortunately, you can't import a class without it being in a package. This is one of the reasons it's highly discouraged. What I would try is a sort of proxy -- put your code into a package which anything can use, but if you really need something in the default package, make that a very simple class which forwards calls to the class with the real code. Or, even simpler, just have it extend.
To give an example:
import my.packaged.DefaultClass;
public class MyDefaultClass extends DefaultClass {}
package my.packaged.DefaultClass;
public class DefaultClass {
// Code here
}
Create a new package And then move the classes of default package in new package and use those classes
- Create a new package.
- Move your files from the default package to the new one.
Create "root" package (folder) in your project, for example.
package source; (.../path_to_project/source/)
Move YourClass.class into a source folder. (.../path_to_project/source/YourClass.class)
Import like this
import source.YourClass;
참고URL : https://stackoverflow.com/questions/2193226/how-to-import-a-class-from-default-package
'programing tip' 카테고리의 다른 글
백분율 값을 보유하기위한 적절한 데이터 유형? (0) | 2020.09.10 |
---|---|
void * a = & a는 어떻게 합법적입니까? (0) | 2020.09.10 |
Objective-C 다중 상속 (0) | 2020.09.10 |
사용자의 Subversion 구성 파일은 주요 운영 체제에서 어디에 저장됩니까? (0) | 2020.09.10 |
파이썬에서 a-= b와 a = a-b의 차이점 (0) | 2020.09.10 |