用註解的方式來解決不同子類的處理問題

2021-08-31 22:45:05 字數 2666 閱讀 6740

最近在寫乙個同父類不同子類的處理方法,例如最簡單的處理number類的時候,假設返回值有不同型別,

如long,double,integer等,並且需要對這些型別有不同的處理方式的時候,一般的情況下,我們可以使用下面這種方式來處理:

if( object instanceof  long)else if(object instanceof double)else if(object instanceof integer)
簡單的方式就可以區分不同子類型別的處理方式了。

不過這種方式很顯然有個缺點,如果需要增加處理新的子型別的時候,需要修改到原有的判斷邏輯,如加上

if( object instanceof  long)else if(object instanceof double)else if(object instanceof integer)else if(object instanceof float)
修改原有邏輯有風險,那麼有沒有其他方式可以既不修改原有的呼叫方式,同時可以滿足處理新增子型別的需求呢?

我們可以試下用註解的方式,如下面**

public class methodinvokerdemo 

@invoke(classtype = double.class)

protected string printdouble(double obj, string username)

@invoke(classtype = long.class)

protected string printlong(long obj, string username)

@invoke(classtype = integer.class)

protected string printinteger(integer obj, string username)

}/**

* 測試入口

* * @param args

*/public static void main(string args)

}

最後的結果如下:

lily  prints double : 1.0

kite prints long : 323

lucy prints integer : 5

我們可以看下具體是怎麼實現的,下面是methodinvoker的實現**:

public class methodinvoker 

/*** 根據子類的註解呼叫對應的方法,如 invoke(new long(1l));

* 則呼叫@invoke(classtype=long.class)對應方法

* 引數型別和個數必須匹配 舉例:

* * @param obj

* @param parameters

* @return

*/protected final object invoke(object obj, object... parameters)

this.refresh();

// 取出所有引數,拼裝成引數陣列

object allparams = new object[1 +

(parameters == null ? 0 : parameters.length)];

if (parameters != null && parameters.length != 0)

}allparams[0] = obj;

// 取出快取的方法表

method method = this.typemethodmap.get(obj.getclass().getname());

if (method == null)

// 設定呼叫許可權為public

try catch (exception es)

// 呼叫該方法並返回結果

try catch (exception e)

}/**

* 重新整理註解和方法的繫結關係

* */

private void refresh()

maptmpmap = new concurrenthashmap();

method methods = this.getclass().getdeclaredmethods();

if (methods != null && methods.length != 0)

tmpmap.put(invoke.classtype().getname(), method);}}

typemethodmap = tmpmap;

}/**

* 子類《註解對應的類名稱,方法物件》快取表

*/private maptypemethodmap = new concurrenthashmap();

}

簡單的繼承methodinvoker即可實現不同的子類使用不同的處理型別,並且不需要修改原有**了,

如需要新增處理float型別,我們只需要增加這個方法:

@invoke(classtype = float.class)    

protected string printinteger(float obj, string username)

c 多種方式讀取檔案(觀察注意處的不同)

要讀取的檔案 逐個字元讀取 方式一 讀取 include includeusing namespace std int main infile noskipws 強制讀入每乙個字元,包括空格 轉折 while infile c i cout endl c i 0 注意,保證strlen c 的值正確...

用file來識別檔案的編碼方式

以前其實也有些類似的需求,就是需要判斷乙個檔案的編碼方式到底是什麼,知道file命令可以,但是遇到某些檔案,比如php它只會顯示這是乙個php檔案,並不會顯示它的編碼方式。今天又重新遇到這個問題,因此仔細看了一下file的手冊。原來file會先根據 usr share file magic裡的一些定...

分庫分表後如何解決不同維度查詢的問題

背景 大家在進行分庫分表的時候應該有碰到乙個問題,乙個資料需要根據兩種維度進行查詢,但是我們在進行分庫分表是只能根據一種維度進行。比如 使用者購買了商品產生了訂單,當使用者非常多的時候,我們會選擇訂單根據下單使用者的id進行分庫分表。但是這裡面存在乙個問題就是作為賣家要如何查詢我賣出的所有訂單呢?因...