简体   繁体   中英

Java need help checking if string is instance

I have an interface, GenericExpression, that gets extended to create expressions (ie AndExpression, OrExpression etc.).

Each GenericExpression implementation has a string that represents it (ie "&", "+", etc.) (stored as a static variable "stringRep")

Is there any way to take a user input String and check if it represents a GenericExpression?

If not (seems likely this is the case), is there any way to achieve a similar effect with a refactored design?

Thanks!

EDIT: Offered a little bit more detail above.

Also, the end goal is to be able to arbitrarily implement GenericExpression and still check if a string represents an instance of one of its subclasses. As such, I can't just store a map of implementation - string representation pairs, because it would make make it so GenericExpression is no longer easily extendible.

Also, this is homework

Well I think you will need to define somewhere what expressions are supported by your program. I think the best way is to use a map , where you map your interface to strings. That way you can easily look up an expression with its representing string. Where you will define this map is dependant on your design. One possibility is a static method in a helper class that resolves expressions to a string like:

Expressions.get("&").invoke(true, false);

Where get is a static method on Expressions that looks up the desired expression in a static map. You will have to initialize this map in a static initializer, or let the expression instances add themselves on creation.

EDIT: (I wanted to comment this on an answer but it seems to be deleted) Personally I don't like the idea of classes registering themselves. It gives me the feeling of not being in control of my code. I would prefer to instantiate the classes in the Expressions class itself. The code for registering a class must be written for every new subclass anyway. I prefer to centralize this code in a single class so if I want to change logic or refactor, I only have to touch one class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM