Using instanceof in java

I am trying to implement a variation of the s-java compiler. To do this, I created several classes that represent different variables. At some point I want to check if such a destination string int a = b legal destination. (b can be any variable). So I create an instance of IntVariable a , and b is an instance of some Variable , and I check b instance of a to see if b can actually be assigned to a. This is just an example of using instanceof , I have a few other cases (b can be a string literal or a number), and I use instanceof to find out if any of the options that I know exist to determine if the assignment is legal .

My question is: can this be done better without using instanceof , or do I just need to live with the fact that although it is not so pretty, it still works, and other ways are much more complicated?

Edit:

 public boolean convertable(Type other) { if (other instanceof FloatType || other instanceof DoubleType) { return true; } return false; } 
+4
source share
2 answers

Since you are working on the s-java compiler, I think that if you get the class object of other , you can do more things

Class otherClass = other.getClass();

Once you have otherClass, you can do:

otherClass.getClasses()

Returns an array containing class objects representing all public classes and interfaces that are members of the class represented by this class object.

OR

otherClass.getDeclaredClasses()

Returns an array of class objects that reflects all classes and interfaces declared as members of the class represented by this class object.

Here is the link:

Java reflection tutorial: http://docs.oracle.com/javase/tutorial/reflect/class/classNew.html

Java reflection API: http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html

0
source

You can also create some unique meta class called "Type" that represents the type. For each specific type (for example, IntType, FloatType) you can create a new class. Then your variable may have a getType () method that returns a reference to a specific type. Now you can directly compare types with "==". Then, “Type” can have a method that returns a list of types in which the first type can be converted.

For instance:

 interface Type { public Collection<Type> getConvertibleTypes(); } 

And then IntType:

 class IntType implements Type { public static final IntType INST = new IntType(); private IntType() { } public Collection<Type> getConvertibleTypes() { Collection<Type> v = new Vector<Type>(); v.add(FloatType.INST); return v; } } 
0
source

Source: https://habr.com/ru/post/1484042/


All Articles