I have a class called "DataModel" or something that basically represents a unit of data, which can be either a string, or a number, or a date or a boolean with different (identical) attributes.
What is the best way to write this model?
Enter a value of type Object
interface DataModel { Object getValue(); // cast to whatever is needed int getValueType(); // uses four constants }
They have four different implementations: "StringModel", "NumberModel", etc., each with its own method, "getValue ()". This means that if you have a DataModel, you will need to specify the correct model to get the value.
interface DataModel { int getValueType(); } interface NumberDataModel extends DataModel { Integer getValue(); } ...
There are four different methods, each of which throws an exception if caused by the wrong type of value:
interface DataModel { String getStringValue(); Integer getIntegerValue(); ... int getValueType(); }
generics. , ... , IllegalStateException , T 4 ...
interface DataModel<T> { T getValue(); }
. .;)
4 - - , , - - , .
1 , / , . , , , int.
, 2 4. 4 , getValueType() , , .
, 3 - , - (, JDBC), , .
4 getValueType() .
.
, - getValue(), , getValue() .
, , . instanceof getValueType(), getValueType, . getValueType, , , int.
4 - . .
, , 4 2. :
interface DataModel<T> { T getValue(); } interface NumberDataModel extends DataModel<Number> { // empty } class NDM implements NumberDataModel { Number getValue() { return ... } }
DataModel / .
As a universal alternative, you can use Class Literals as Runtime tokens and use newInstance()to get data instances with a security type. This allows you to check the compilation time using general parameters and check the runtime through isAssignableFrom().
newInstance()
isAssignableFrom()
Source: https://habr.com/ru/post/1728304/More articles:Ajax Control Toolkit HTML Editor setup task? - c #есть ли интерфейс ruby для сервера проектов ms? - rubyHTTPS with self-signed certificate in keychain application - iphoneforeach throws an exception, why? - listMechanize on site https - ruby | fooobar.comКак создать структуру автоматизации для базы данных - databasehaskell exercise, type detection and protection - haskellJSLint No need to initialize undefined - javascriptHow to force screen refresh for UIScrollView from a stream / function other than UI (iPhone) - iphoneHow do you identify users when using PayPal? - paypalAll Articles