The way to work around this problem is to check the type using instanceof and use a cast. Like this:
private void initialize(HttpRequestBase method)
{
if(method instanceof HttpPost)
{
String body = "body";
HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8"));
((HttpPost) method).setEntity(entity);
}
}
But whenever you use a cast, you should consider that there may be a more elegant solution. In this case, I would argue that a more elegant solution would be to use method overloading and have a specific method for HttpPost instances.
private void initialize(HttpPost method)
{
String body = "body";
HttpEntity entity = new ByteArrayEntity(body.getBytes("UTF-8"));
method.setEntity(entity);
}
Of course this would mean you would need a separate method for HttpGet (and any other subclasses of HttpRequestBase you wish to support). Any common code shared between GET and POST should be extracted into smaller methods that are called by both initialize() methods.
private void initialize(HttpGet method)
{
// ...
}
This, of course, you might argue defeats the whole point of trying to create one handler for both GET and POST. And you would be right. But you should then question the entire exercise of trying to create one method that handles both. Perhaps the most elegant design is to treat them separately. After all, that is precisely what the authors of the framework you're using chose to do.
ifcondition will never be true, don't you? Any existing object reference compared with a new object will returnfalse.if(method instanceof HttpPost)instanceof. Then you'll also be able to cast. But this is very basic Java. Perhaps you should review Inheritance.