Java的Covariance设计原理和SAP ABAP的模拟实现-阿里云开发者社区

开发者社区> c位出道> 正文

Java的Covariance设计原理和SAP ABAP的模拟实现

简介: Java的Covariance设计原理和SAP ABAP的模拟实现
+关注继续查看

I am the trainer of one standard course “Programming Language Concept” within SAP and there is a set of concept Covariance and Contravariance, which has only built-in support by a subset of programming language like Java. For those ABAPers who don’t have chance to touch this concept in their daily work, I have built a small example to simulate how the concept works in ABAP as well for ease of understanding. The example explained in this example is just a prototype purely for training and education purpose.


Covariance and Contravariance in computer science

Both concept are closely related to inheritance in Object-Oriented world.

In this blog I use the following classes with hierarchical inheritance relationship.


image.pngIt is very straight-forward that both Dog and Cat are a kind of sub class of Animal, and ToyDog is a sub class of Dog.


However, how about the relationship between Animal container and Dog container? In order to describe the sub-typing relationship among more complex types ( in my example above, complex types mean Animal container and Dog container ) built via component type ( in my example component types refers to class Animal and Dog ).


You can find the definition of concept Covariance and Contravariance in Wikipedia.


Covariance

the complex type preserves the inheritance ordering of component type, which orders types from more specific to more generic. For example, we already have prerequisite that Dog is a sub class of Animal, and if Dog container is also a sub class of Animal container, we now say the subtyping relationship between Dog container and Animal container fulfills the Covariance contract.


Contravariance

Reverses this ordering.

In this blog, I will only focus on Covariance, since Contravariance works the same way as Covariance except that the inheritance relationship of complex types is reverted.


Covariance in Java

See this example below. In line 126, in signature of method forABAPer,

List<? extends Dog> declares a List container which must adhere to Covariance contract. ABAPers can analogize the symbol “?” to the generic type in ABAP such as ANY, ANY TABLE etc, which acts as a place holder and variable with concrete data type must be filled as parameter when the method is consumed.


List<? extends Dog> in method signature means the method can only accept a list container which fulfills Covariance contract, that is, the actual type of ? must be Dog itself, or any other sub class of Dog.


Due to Covariance contract, the Dog container created in line 113 and Toy Dog container in line 117 pass the syntax check, it is ok to call both via method forABAPer. For cat container in line 121, since Cat is not a sub class of Dog, syntax error is raised accordingly.


image.pngContravariance contract, on the other hand, is defined via

“<? super T>“, where T is a generic COMPONENT type of super class, and ? is the concrete type you must specify when you call the method.


Covariance and Contravariance is widely used in JDK implementation and many Java framework like Spring.


See one example below about the implementation of utility method java.util.Collections.copy, which does a shadow copy of each element from source container to destination container.


image.pngAnother guideline of Covariance and Contractvariance is the so called PECS https://en.wikipedia.org/wiki/Wildcard_(Java) which is much more sophisticated and is out of scope of this blog.


How to simulate Covariance in ABAP

In ABAP since we don’t have real container type with Object-Oriented behavior, we have to simulate Covariance with internal table plus interface instead.


(1) declare a tag interface


I declare a tag interface ZIF_COVARIANCE without any method defined there, but only with two attribute G_TYPE and C_TYPE.

Here G_TYPE simulates generic type of list container and C_TYPE simulates concrete type “?” in Java, which must be filled by a real data type when method is called.


image.png(2) build a Animal container with Covariance contract


In this container class, I assign the tag interface ZIF_COVARIANCE to it, meaning that this container is now under the Covariance syntax check.


The generic type G_TYPE is now determined in the design time, ZCL_DOG.

This means in compiler time, only Covariance compliant code can pass syntax check:


When you instantiate a new instance of this animal container, the concrete class type you use must be either ZCL_DOG itself, or any sub class of ZCL_DOG.


When you try to add a new animal to this animal container, the data type of the element to be inserted must be either ZCL_DOG itself, or any sub class of ZCL_DOG.


image.png(3) implement a custom Covariance syntax check


In this animal container class, I use an internal table with type ZCL_ANIMAL to store the inserted animal reference.

types TY_REF type ref to ZCL_ANIMAL .

data: DATA type STANDARD TABLE OF ty_ref .

As a result, by default the following code will pass the syntax check, since ZCL_CAT is also a sub class of ZCL_ANIMAL, so the instance of it could be successfully inserted to internal table with TYPE REF TO ZCL_ANIMAL, although this is a violation of Covariance.

There are two places in the following code which do not obey Covariance:


In line 4, since the animal container has already marked generic type as ZCL_DOG, the concrete data type must be either ZCL_DOG itself, or any sub class of ZCL_DOG. ZCL_CAT is not allowed.


In line 11, it is not allowed to insert a cat to a dog container.


image.pngThe expected behavior is: once you click Ctrl+F2 to trigger syntax check, all Covariance violation are found and listed, see example below:image.pngHow to implement Covariance Syntax check in class builder

The main logic of Covariance check is done in method ZCL_ABAP_COVARIANCE_TOOL~COVARIANCE_SYNTAX_CHECK, which only consists of 45 lines:


METHOD covariance_syntax_check.

   DATA: lv_include TYPE progname,

         lv_main    TYPE progname,

         lv_index   TYPE int4 VALUE 1.

   FIELD-SYMBOLS:<method> LIKE LINE OF mt_result.

   initialize( ).

   ms_working_method = is_method_def.

   fill_method_source( ).

   lv_include = cl_oo_classname_service=>get_method_include( is_method_def ).

   lv_main = cl_oo_classname_service=>get_classpool_name( is_method_def-clsname ).

   DATA(lo_compiler) = NEW cl_abap_compiler( p_name = lv_main p_include = lv_include ).

   lo_compiler->get_all( IMPORTING p_result = mt_result ).

   LOOP AT mt_result ASSIGNING <method>.

     CASE <method>-tag.

       WHEN 'ME'.

         DATA(ls_method_detail) = get_method_type( <method>-full_name ).

         fill_caller_variable_name( EXPORTING iv_current_index = lv_index

                                    CHANGING  cs_method_detail = ls_method_detail ).

         IF ls_method_detail-method_signature IS NOT INITIAL.

           fill_call_parameter( EXPORTING iv_current_index = lv_index

                                   CHANGING cs_method_detail = ls_method_detail ).

         ENDIF.

         ls_method_detail-line = <method>-line.

         APPEND ls_method_detail TO mt_method_detail.

       WHEN OTHERS.

     ENDCASE.

     ADD 1 TO lv_index.

   ENDLOOP.

   DELETE mt_method_detail WHERE caller_variable_name IS INITIAL.

   LOOP AT mt_method_detail ASSIGNING FIELD-SYMBOL(<result>).

     CHECK is_covariance_check_needed( <result>-caller_variable_name ) = abap_true.

     CASE <result>-method_type.

       WHEN cs_method_type-constructor.

         check_ctor_covariance( <result> ).

       WHEN cs_method_type-instance.

         check_instance_covariance( <result> ).

     ENDCASE.

   ENDLOOP.

   RT_ERROR_MESSAGE = MT_ERROR_MESSAGE.

 ENDMETHOD.(1) perform syntax analysis on instance method and constructor method


With help of CL_ABAP_COMPILER, I can get a list of all methods call and used variable within the method being checked. The used information returned by CL_ABAP_COMPILER has the following format.

As the Covariance check only makes sense on method call,



image.pngso in my Covariance syntax analysis, I will only handle the entry for method call ( marked with tag “ME” in CL_ABAP_COMPILER returning result ).



image.pngAfter the loop in line 17 is finished, I have successfully regularized the result from CL_ABAP_COMPILER with raw format to my customized data format as below:



image.pngThe internal table mt_method_detail has line type defined by myself, TY_METHOD_DETAIL.


Take the first row in above screenshot for example

Method_type 1 means it is a constructor call.

CALLER_VARIABLE_NAME lo_dog_container means this variable is instantiated via keyword NEW.


METHOD_CLS_NAME ZCL_ANIMAL_CONTAINER means the variable lo_dog_container is initialized by NEW with type ZCL_ANIMAL_CONTAINER.

CALL_PARAMETER_NAME ZCL_DOG means the string literal “ZCL_DOG” is passed into constructor as a parameter.


Take record with index 6 in above screenshot for illustration

Method_type 2 means it is an instance method call.

CALLER_VARIABLE_NAME lo_dog_container means it is this variable which performs the current instance method.

METHOD_CLS_NAME ZCL_ANIMAL_CONTAINER means the instance variable lo_dog_container has class type ZCL_ANIMAL_CONTAINER.


METHOD_NAME ADD means the instance method being called has name “ADD”.

CALL_PARAMETER_NAME LO_CAT means the instance lo_cat is passed into instance method ADD.


(2) perform the real Covariance check based on regularized method call information generated in previous step


Since now the essential information for Covariance check, the generic type and concrete type are already available, it is ready to perform check.

(2.1) Covariance relevance check


I just loop every record and first check whether the current method call is relevant for Covariance check. I am using the assumption that a method call should only be checked against Covariance when the class of the instance which performs the call has been assigned with tag interface ZIF_COVARIANCE.



image.png(2.2) Covariance check implementation by evaluate the relationship between generic type and concrete type


The evaluation is done in method below: if generic type and concrete type does not fulfill Covariance, syntax error is reported.


image.pngHow to play around with this prototype by yourself

(1) Follow my blog Implement Custom Syntax Check in SAP GUI to setup necessary configuration create a new custom syntax check handler class ZCL_WB_CLEDITOR( source code could be found from my github mentioned above ).


(2) Create a class with any name and a new method with following source code:


  METHOD main.

   DATA(lo_dog_container) = NEW zcl_animal_container( iv_concrete_type = 'ZCL_DOG' ).

* concrete type must be ZCL_DOG or its subclass!

   DATA(lo_cat_container) = NEW zcl_animal_container( iv_concrete_type = 'ZCL_CAT' ).

   DATA(lo_cat) = NEW zcl_cat( ).

   DATA(lo_dog) = NEW zcl_dog( ).

   DATA(lo_toydog) = NEW zcl_toydog( ).

* only dog or dog subclass instance is allowed for insertion

   lo_dog_container->add( lo_cat ).

   lo_dog_container->add( lo_dog ).

   lo_dog_container->add( lo_toydog ).

 ENDMETHOD.(3) In Class builder under Form-based mode, press Ctrl+F2 and you should see two error messages for Covariance violation:

image.pngFurther reading

I have written a series of blogs which compare the language feature among ABAP, JavaScript and Java. You can find a list of them below:


Lazy Loading, Singleton and Bridge design pattern in JavaScript and in ABAP

Functional programming – Simulate Curry in ABAP

Functional Programming – Try Reduce in JavaScript and in ABAP

Simulate Mockito in ABAP

A simulation of Java Spring dependency injection annotation @Inject in ABAP

Singleton bypass – ABAP and Java

Weak reference in ABAP and Java

Fibonacci Sequence in ES5, ES6 and ABAP

Java byte code and ABAP Load

How to write a correct program rejected by compiler: Exception handling in Java and in ABAP

An small example to learn Garbage collection in Java and in ABAP

String Template in ABAP, ES6, Angular and React

Try to access static private attribute via ABAP RTTI and Java Reflection

Local class in ABAP, Java and JavaScript

Integer in ABAP, Java and JavaScript

Covariance in Java and simulation in ABAP

Various Proxy Design Pattern implementation variants in Java and ABAP

Implement CGLIB in ABAP


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
阿里云服务器怎么设置密码?怎么停机?怎么重启服务器?
如果在创建实例时没有设置密码,或者密码丢失,您可以在控制台上重新设置实例的登录密码。本文仅描述如何在 ECS 管理控制台上修改实例登录密码。
10076 0
使用NAT网关轻松为单台云服务器设置多个公网IP
在应用中,有时会遇到用户询问如何使单台云服务器具备多个公网IP的问题。 具体如何操作呢,有了NAT网关这个也不是难题。
26789 0
阿里云服务器如何登录?阿里云服务器的三种登录方法
购买阿里云ECS云服务器后如何登录?场景不同,阿里云优惠总结大概有三种登录方式: 登录到ECS云服务器控制台 在ECS云服务器控制台用户可以更改密码、更换系.
13884 0
windows server 2008阿里云ECS服务器安全设置
最近我们Sinesafe安全公司在为客户使用阿里云ecs服务器做安全的过程中,发现服务器基础安全性都没有做。为了为站长们提供更加有效的安全基础解决方案,我们Sinesafe将对阿里云服务器win2008 系统进行基础安全部署实战过程! 比较重要的几部分 1.
9158 0
腾讯云服务器 设置ngxin + fastdfs +tomcat 开机自启动
在tomcat中新建一个可以启动的 .sh 脚本文件 /usr/local/tomcat7/bin/ export JAVA_HOME=/usr/local/java/jdk7 export PATH=$JAVA_HOME/bin/:$PATH export CLASSPATH=.
4659 0
阿里云ECS云服务器初始化设置教程方法
阿里云ECS云服务器初始化是指将云服务器系统恢复到最初状态的过程,阿里云的服务器初始化是通过更换系统盘来实现的,是免费的,阿里云百科网分享服务器初始化教程: 服务器初始化教程方法 本文的服务器初始化是指将ECS云服务器系统恢复到最初状态,服务器中的数据也会被清空,所以初始化之前一定要先备份好。
7365 0
阿里云服务器ECS登录用户名是什么?系统不同默认账号也不同
阿里云服务器Windows系统默认用户名administrator,Linux镜像服务器用户名root
4503 0
+关注
2316
文章
0
问答
来源圈子
更多
+ 订阅
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载