Forced Downcasting in Java

I want to force a downcast on a object what can't be down casted and was wondering what the right approach would be. The use case is that I have a list of rules that are checked and what will generate a list of failed rule. A failed rule is a subclass of a rule. But downcasting like FailedRule failedRule = (FailedRule) rule;

will fail because the rule object is not an instanceof FailedRule

To work around this I instantiate a clone; FailedRule failedRule = new FailedRule (rule);

and my FailedRule class looks like this

public class FailedRule extends Rule{

 *force a down cast from Rule to FailedRule through cloning
public FailedRule (Rule upcast){
   super.setRuleCode( upcast.getRuleCode());

Is there a easier way to do this? To answer myself, the design is flawed, the code should be:

public class FailedRule{
  private Rule rule;
  public setRule(Rule rule){


This is probably a symptom that your inheritance hierarchy is weakly designed. You're trying to introduce mutability of attributes through inheritance (a Rule has "failed" if it is an instance-of FailedRule). Inheritance isn't really good for that sort of thing.

I would say you should either use composition (a FailedRule has a Rule as a source) or that failed should be a boolean attribute of an instance of Rule.

Use a method that converts any rule to a FailedRule:

public static FailedRule asFailedRule(Rule rule){
    return (rule instanceof FailedRule)
    ? (FailedRule) rule
    : new FailedRule(rule)

(If the rule is already a FailedRule, cast and return it, otherwise use it to construct a FailedRule)

Need Your Help

Flatten expression algorithm

python string dictionary

I cant find any good algorithm to flatten values given in dict. My expression is a string with 'variables'. Each variable can be a number or another variable i.e:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.