Java obtains generic types

Source: Internet
Author: User

Java method for retrieving generic types: Generally, a generic type name is obtained, assembled, and a Bean is obtained from the spring container Based on the name. For example, [java] @ Service ("baseService ") public class BaseService <T> implements BaseMapper <T> {private String mapper; @ Override public int insert (T t) {BaseMapper <T> baseMapper = (BaseMapper) SysConfigHelper. getAppContext (). getBean (t. getClass (). getSimpleName (). toLowerCase () + "Mapper"); return baseMapper. insert (t) ;}}like the above T, you can get the T type value as User, that is, t. getClass (). getSimpleName (). the result of toLowerCase () + "Mapper" is [userMapper], but when the delete method is used, this method is not applicable to [java] <pre name = "code" class = "java"> @ Override public int deleteById (int id) {T t = null; baseMapper <T> baseMapper = (BaseMapper) SysConfigHelper. getAppContext (). getBean (t. getClass (). getSimpleName (). toLowerCase () + "Mapper"); return baseMapper. deleteById (id) ;}</pre> in this way, an exception is thrown, because t is nul. We can write [java] @ Override public int update (T t) {Type type = getClass (). getGenericSuperclass (); Type trueType = (ParameterizedType) type ). getActualTypeArguments () [0]; Class <T> entityClass = (Class <T>) trueType; System. out. println (type); System. out. println (trueType); System. out. println (entityClass. getSimpleName (); BaseMapper <T> baseMapper = (BaseMapper) SysConfigHelper. getAppContext (). getBean (entityClass. getSimpleName (). toLowerCase () + "Mapper"); return baseMapper. update (t);} The result printed on the console is: [java] com. zte. framework. jdbc. baseService <com. zte. user. domain. user> class com. zte. user. domain. the User obtains the generic T type. The value is [User]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.