lundi 5 décembre 2022

Test at runtime if a cast would compile

Given two java.lang.Class objects dst and src and assuming that they represent the types Y and X respectively, I would like a function public static boolean isCastCompilable(Class dst, Class src) that returns true if and only if the statements X x; Y y = ((Y)x); would compile for those types X and Y.

Here is a first attempt at hand-coding these rules:

public class Compilable {

    public boolean isCastCompilable(Class dstClass, Class srcClass) {
        if (Objects.equals(srcClass, dstClass)) {
            return true;
        }
        
        if (Boolean.TYPE.equals(srcClass)) {
            return false; // Boolean cannot be converted explicity to any primitive type:
            // https://javajee.com/casting-of-primitives-in-java
        }

... more code

        return false;
    }
}

For instance, this function would return true for isCastCompilable(java.util.List.class, java.util.ArrayList.class) because the statements java.util.ArrayList x; java.util.List y = ((java.util.List)x); would be valid Java code that a compiler would accept.

It should return false for isCastCompilable(Boolean.TYPE, String.class) because String x; boolean y = (boolean)x; would be rejected by the compiler.

My question: Is there a straight-forward way of implementing isCastCompilable or will I have to handcode all the casting rules myself, the way I started doing in the code example above?

Context: I am making a kind of Java code generator and would like to test if the code that performs casts will compile in order not to emit invalid code.





Aucun commentaire:

Enregistrer un commentaire