2016-08-12 72 views
3

通常你創建一個protobuf的類的實例是這樣的:如何使用java反射創建protobuf實例?

Bar.Builder bld = Bar.newBuilder(); 
bld.setXYZ(... 

我有一個使用Java反射來實例化的protobuf類的用例:

Class clsBar = Class.forName("com.xyz.Foo$Bar"); 
Object instance = clsBar.newInstance(); // error here! 
Method mth = clsBar.getMethod(...); 

上面的代碼工作正常與正常的Java類。但是對於生成的protobuf類"com.xyz.Foo$Bar",它給了我一個NoSuchMethodException,因爲那裏沒有默認的公共構造函數。

有關如何使用Java反射創建protobuf實例的任何建議?問題在於那些擅長protobuf內部構件的人。謝謝!

+0

如果您調用clsBar.getConstructors()並在返回的構造函數對象之一上調用.newInstance()方法,該怎麼辦? – Duston

+0

你有什麼信息?只有期望的課程或更多?如果你想從字節數組或類似的地方創建一個Protobuf實例,你可以使用'parseFrom'方法。 – dpr

+0

@Duston所有的構造函數都是私有的,就像protobuf實現一樣。對於dpr,我只有生成protobuf類的全限定類名。 –

回答

3

我覺得你應該去充分的方式:通過生成器類:

//get Bar class 
Class barClass = Class.forName("com.xyz.Foo$Bar"); 

//instantiate Builder through newBuilder method 
Method newBuilderMethod = barClass.getMethod("newBuilder"); 
Bar.Builder builder = (Bar.Builder) newBuilderMethod.invoke(null); 

// ... set properties -- can be through reflection if necessary 

//build: 
Bar bar = builder.build(); 

雖然我不完全看反射是如何在這種情況下,任何使用,這可能會需要更深入的瞭解你正試圖解決的確切問題。

+1

你的回答是正確的,但有一個小錯誤:「newBuilder」方法屬於'Bar'類,而不是'Bar $ Builder'。謝謝! –

+0

@NathanW糾正了它 - 似乎我沒有給予足夠的重視...... – ppeterka