PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, April 28, 2022

[FIXED] How to fix 'Unchecked cast from MyClass to T'

 April 28, 2022     generics, java, list, warnings     No comments   

Issue

I have a method that works, but give me a warning, is there any solution to remove it, cleanly?

  • In this method I call the method :
    <T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)
    That return an object that extends SonarContainPaging.

  • I try to add an object that extends SonarContainPaging to my list, but I get a warning.

  • The SonarContainPaging object has a method canContinuePaging that takes a page integer and return a boolean.


The warning:

Type safety: Unchecked cast from SonarContainPaging to T

private <T extends SonarContainPaging> void getSonarListContainingPaging(String url, Map<String, Object> uriVariables, 
        Class<T> klass, List<T> list) {
    int page = 1;
    SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
    page++;

    list.add((T)sonarObject); // Warning
    while (sonarObject.canContinueLooping(page)) {
        sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
        page++;

        list.add((T) sonarObject); // Warning
    }
}

Any solution you can think of?


The solution given by @Sweeper is to change the type of sonarObject to T
The error I made, was assuming that a generic T object could not call method from its parent.


Solution

The solution is to use T as the type here and then you can remove your casts:

// before:
// SonarContainPaging sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);
// after:
T sonarObject = getSonarObjectFromPage(url, uriVariables, klass, page);

Since according to your comment, getSonarObjectFromPage returns T, where T is the class you pass it in:

<T extends SonarContainPaging> T getSonarObjectFromPage(String url, Map<String, Object> uriVariables, Class<T> klass, List<T> page)

In this case you passed the class klass, which is a Class<T>, so getSonarObjectFromPage will return a T as well.



Answered By - Sweeper
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing