Answer the question
In order to leave comments, you need to log in
How to determine the type of an expression written in java?
Good afternoon.
I am writing a template engine that translates the template code into java code and then compiles it using javax.tools. Please leave the question of expediency.
I would like to add an automatic output of the expression type to the template engine.
For example, there is a templating command (commands are enclosed in back quotes):
`for x: dataSource.getUsers(true)`
...
`/for`
// В данном коде dataSource.getUsers(true) - это некий метод, который возвращает Iterable<User>
for(User x: dataSource.getUsers(true)) {
out("\n...\n");
}
`for x: dataSource.getUsers(true)`
`for x: ("1,2" + ",3").split(",")`
Answer the question
In order to leave comments, you need to log in
Put yourself in the place of the translator.
When you read the line `for x: dataSource.getUsers(true)` you should know what dataSource is - what type it is, what getUser returns, and whether it even exists.
Where can you find out? - From the text of the program. I note that the values in Wildcard <> at runtime are already unknown.
For the dataSource example, this should be described somewhere in the code: a class field definition or a local variable. If this information is not available, it means that you yourself do not know this and you cannot teach the compiler.
Agree if I write for x: foo.getBar('1'). you will not understand what it is and ask: "where is foo declared and what does the method return." This requires source code (maybe you already understand this).
For example with "1,2" + ",3"
What to do next: You practically need a java parser/compiler. For this I would look towards AST (Abstract Syntax Tree) from Eclipse. Not the most convenient API and you can easily write bad code, but it will solve the problem 100%.)
With it, you can parse the text to a template, find out the type of the variable and the type of the return value, and get the type in <>.
It will be similar with strings, only the type can be obtained immediately, without parsing the rest of the code, since it is known that the literal of the String type and all methods of this type are known to everyone.
I hope at least something is clear.
By the way, what you are trying to do has already been implemented in a similar form in a stray called Xtend.
https://eclipse.org/xtend/documentation/203_xtend_...
Perhaps this will help you, though their documentation is warped ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question