How to determine the type of an expression written in java?

Good afternoon.

Write a template engine which translates template code into java code and then compiles with Please leave the question of expediency.

Want in the template add automatic type inference of expressions.
For example, a team of the template (commands are enclosed in back-quotes):
`for x: dataSource.getUsers(true)`
// In this code, the dataSource.getUsers(true) is a method which returns Iterable<user></user>

Broadcast Java it has:
for(User x: dataSource.getUsers(true)) {

Variations of the expression can be anything:
`for x: dataSource.getUsers(true)`
`for x: ("1,2" + ",3").split(",")`

Question: when I broadcast to understand what type of element will return the expression for?
July 2nd 19 at 13:40
1 answer
July 2nd 19 at 13:42
Put yourself in the place of translator.
You are reading a string `for x: dataSource.getUsers(true)` must know what dataSource - what kind is it that getUser returns and generally he is there.
Where can you learn? - From the program text. Notice that the values in the Wildcard <> in runtime is already known.
For example, with a dataSource this should be described somewhere in the code: define class fields or local variable. If this information is not available, it means that you do not know and to teach the compiler can't.
Agree, if I write for x: foo.getBar('1'). you will not understand it and ask: "where foo is declared and that method returns". For this you need the source code (perhaps you understand it) .

For example, "1,2" + ",3", the type is clear from context.

What to do: you practically need parser/compiler in java. I would for this he looked towards the AST (Abstract Syntax Tree) from the Eclipse. Not the most convenient API and it's easy to write bad code, but it 100% will solve the problem.)

With the help of it you can parse the text to the template to find the variable type and return type, and to type in <>.
Strings will be similar, only the type directly, without parsing the rest of the code, since it is known that the literal is of type String and all methods of this type are known to all.

I hope at least something understandable.

The word that you're trying to do has already been implemented in similar form in Pribluda called Xtend.
Perhaps it will help, though the documentation they have warped...

Find more questions by tags Java