導航:首頁 > 方法技巧 > 如何將方法封裝成介面

如何將方法封裝成介面

發布時間:2023-04-23 21:07:01

① java怎麼封裝介面

我們先來封裝以前定義的Human類:
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human(160);
System.out.println(aPerson.getHeight());
aPerson.growHeight(170);
System.out.println(aPerson.getHeight());
aPerson.repeatBreath(100);
}

}

class Human
{
/**
* constructor
*/
public Human(int h)
{
this.height = h;
System.out.println("I'm born");
}

/**
* accessor
*/
public int getHeight()
{
return this.height;
}

/**
* mutator
*/
public void growHeight(int h)
{
this.height = this.height + h;
}

/**
* encapsulated, for internal use
*/
private void breath()
{
System.out.println("hu...hu...");
}

/**
* call breath()
*/
public void repeatBreath(int rep)
{
int i;
for(i = 0; i < rep; i++) {
this.breath();
}
}

private int height; // encapsulated, for internal use
}

② java如何把一個已經實現某些具體功能的類封裝成一個介面供其他的程序進行使用

第一:具體的功能方法如果是public直接就可以用import引入該類然後調用
第二:如果這功能是類似於.exe可執行文件或者打包成了.jar的可執行文件,那麼Java中有固定的代碼可以內嵌運行已經實現功能的程序
第三:如果你說的其他程序,是指用別的語言寫的,那麼可以用相關工具將該Java程序打包成.jar,然後安裝了Java運行環境後就可以當成.exe文件運用。
第四:如果僅僅只是想把已經寫好的Java程序,該程序已經實現了具體功能,然後你想用其他語言來調用該功能,這就需要網上再找下有這種工具沒了?Java中的JNI和JNA相關技術可以研究下,我只知道人工編寫新代碼。

③ C庫如何封裝成C++介面

C一般不能直接調用C++函數庫,需要將C++庫封裝成C介面後,才可以使用C調用。
下面舉例,說明一個封裝策略:

//code in add.cxx
#include "add.h"
int sample::method()
{
cout<<"method is called!\n";
}
//code in add.h
#include
using namespace std;
class sample
{
public:
int method();
};
將上面的兩個文件生成動態庫libadd.so放到蔽仿 /usr/lib目錄下,編譯命令如下:
sudo g++ -fpic -shared -g -o /usr/lib/libadd.so add.cxx -I ./
由於在C中不能識別類,所以要將上面類的成員函數,要封裝成C介面函數才能被調用。缺豎下面進行封裝,將輸出介面轉換成C介面。
//code in mylib.cxx
#include "add.h"
#ifndef _cplusplus
#define _cplusplus
#include "mylib.h"
#endif

int myfunc()
{
sample ss;
ss.method();
return 0;
}
//code in mylib.h
#ifdef _cplusplus
extern "C"
{
#endif

int myfunc();

#ifdef _cplusplus
}
#endif
在linux下,gcc編譯器並沒用變數_cplusplus來區分是C代碼還是C++ 代碼(沒有宏定義),如果使用gcc編譯器,這里我們可以自己定義一個變數_cplusplus用於區分C和C++代碼,所以在mylib.cxx中定義 了一個變數_cplusplus用於識別是否需要「extern "C"」將函數介面封裝成C介面。但是如果使用g++編譯器則不需要專門定義_cplusplus,編譯命令如下:
g++ -fpic -shared -g -o mylib.so mylib.cxx -la -I ./
main.c
#include

#include
#include "mylib.h"

int
main()
{
int (*dlfunc)();
void *handle; //定義一個句柄
handle = dlopen("./mylib.so", RTLD_LAZY);//獲得庫句柄
dlfunc = dlsym(handle, "myfunc"); //獲得函數入口
(*dlfunc)();
dlclose(handle);

return 0;
}
編譯命令如下:
gcc -o main main.c ./mylib.so -ldl
下面就可以執行了。
需要說明的是,由於main.c 和 mylib.cxx都需要包含mylib.h,並且要將函數myfunc封裝成C介面函數輸出需要「extern "C"」,而C又不識別「extern "C"」,所以需要定義_cplusplus來區別處理mylib.h中的函數myfunc。
在伏並大main.c的main函數中直接調用myfunc()函數也能執行,這里介紹的是常規調用庫函數的方法。

閱讀全文

與如何將方法封裝成介面相關的資料

熱點內容
有什麼方法在兩天賺一萬塊錢 瀏覽:524
如何給新聞擬標題方法 瀏覽:996
斜移換擋正確方法視頻 瀏覽:583
臍帶保護帶的使用方法 瀏覽:557
鴻雁120電腦模塊接線方法 瀏覽:143
腋臭的鍛煉方法 瀏覽:17
奇門預測的分析判斷方法 瀏覽:777
鋼筋閃光對焊最常用的一種方法 瀏覽:222
江蘇選調生簡單方法 瀏覽:1001
模具製造的研究方法 瀏覽:65
七步絕殺正確方法 瀏覽:327
間接測量方法的局限性 瀏覽:527
如何記住模塊的方法 瀏覽:870
人類學進化論學派的研究方法 瀏覽:878
女孩子用什麼方法去除鬍子 瀏覽:887
手機殼排線方法 瀏覽:56
測量儀器的使用方法圖文 瀏覽:251
膠體金標記免疫試紙條檢測方法 瀏覽:326
轎車鋪車底最佳方法 瀏覽:126
速啪洗鞋神器使用方法 瀏覽:984