I have a class Foo
public class Foo {
String property1;
int property2;
Object property3;
List<String> property4;
}
Now I would like to copy the names of the properties to class Bar.
public class Bar {
property1
property2
property3
property4
}
Obviously, this code does not compile, but the goal is to call a template to generate some code. When copying valid Java code, there is no problem. Unfortunately, probably because this code does not compile, when copying the selected properties from Foo in a Java source File, the indentation of class Bar is not like this, but:
public class Bar {
property1
property2
property3
property4
}
Is there a way to get those properties in one column in a Java File?
I'm assuming the templates you want to call simply insert the type before a field.
In that case you could:
use F2 to navigate through each error
fill in the type
ctrl+shift+enter ("Complete current statement" action) to add the missing semicolon and properly indent the line
Or you could also:
select the copied property names
unindent them all the way (now they are aligned)
reindent them
I found a solution, which seems to be an improvement over the current way.
It is possible to do a "Paste Simple" in Intellij using Ctrl+Alt+Shift+V. This way, Intellij does no-auto formatting. So when the cursor is at the start of the line, a block is inserted.
After that, it is possible to call the templates and only when having valid Java Code, I can call Ctrl+Alt+L to reformat the code.
Related
I am currently practicing in developing kotlin and as of now I seem to get confused with kotlin's class structure.
this is a code in java
//properties
private String var;
//constructor
public SampleClass(String var){
this.var = var;
}
public SampleClass(){
}
//getters and setters
public String getVar(){
return this.var;
}
public String setVar(String var){
this.var = var;
}
what's the kotlin equivalent of this ?
This is the equivalent Kotlin code for your Java code:
class SampleClass(var `var`: String? = null)
There are a few things to note:
Your Java snippet above omits the wrapping class SampleClass code
Your setVar() indicates that it returns a String, but it's actually void. I assume you intended for it to have a void return type.
Your property var is not ideal for Kotlin, because it's a reserved word. That's why we have to escape it with backticks. (It could also be kind of confusing in Java 10, since var is a reserved type name there now).
Here's why this one-liner is equivalent to the Java listing.
The constructor part - the part between the parentheses - can be used to accept constructor arguments, but by putting the Kotlin keyword var at the beginning, we tell Kotlin that we want this to also be a property. Kotlin will create a getter and setter for it.
The String? part makes this property of type nullable String.
Instead of creating two different constructors, we just give our var property argument a default value of null by using = null. When creating this class from Java, it'll still show up as two constructors.
If you're using IntelliJ or Android Studio, you can tell it to convert any Java class to Kotlin. Just open the class file, and go to the Code menu, and choose Convert Java file to Kotlin file. It won't necessarily generate very idiomatic code (e.g., it might create two constructors instead of using a default for the constructor argument), but it'll get you started.
For "what is Kotlin equivalent of some code in Java", there is an universal answer: copy the Java code and paste it into a Kotlin file in IDEA/Android Studio. Or convert the entire file.
On the web, you can use https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Java%20to%20Kotlin%20conversion/Task.kt.
I'm looking for a way to set up code formatting to keep javadoc in enums in separate blocks. Right now wrapping of enum members works as intended, but for some reason javadoc comments start/end on the same line as the members
I'd keep getting this:
public enum FormatTest {
FOO, /**
* some description
*/BAR, BAZ;
}
but I want it to look something like this:
public enum FormatTest {
FOO,
/**
* docs either like this
*/
BAR,
/** or like this */
BAZ;
}
It works perfectly well for class members strangely enough...
try changing the Code Style settings.
In IntelliJ, go to: Settings -> Code Style -> Java -> Wrapping and Braces tab.
Scroll down untill you see Enum constants, and change the value to: Wrap always.
See screenshot
Let's say that I have a class class Foo : Base and I want to perform a certain method call with signature
public void someStuf(Iterable<? extends Base> param)
For the search template I just take as starting point the pre-existing one
$Instance$.$MethodCall$($Parameter$)
Is it possible to match a parameter of any kind Iterable of a specific Base subclass (Foo in this example)??
List<Foo> fooList = new ArrayList<>();
fooList.add(new Foo("A"));
List<Bar> barList = new ArrayList<>();
barList.add(new Bar(1));
someStuff(fooList); // find this!
someStuff(barList); // don't find this one
someStuff(Collections.singletonList(new Foo("B"))); // also match this one
I've tried several combinations without any luck, is it even possible to do?
This was previously not possible without resorting to a hack. See further below for that. Currently, the code can be found using a Type modifier.
search template
$Instance$.$MethodCall$($Parameter$)
variables
$Instance$ Count=[0,1]
$MethodCall Text=someStuff
$Parameter$ Type=Iterable<Foo>, within type hierarchy
hack
The hack previously needed used a Script modifier and a simple Type modifier on the $Parameter$ variable:
$Parameter$
Script=__context__.type.parameters[0].presentableText.contains("Foo")
Type=Iterable
The related bug report is fixed since IntelliJ IDEA 2017.3.
Newbie question on IntelliJ plugin development.
I need to generate a parameterised class (Class with generics) given the name of the class and the name of the type parameter, but I can not find how to?
It seems PSIClass does not support generics.
Example
Given
String className = "MyClass";
String typeName = "T"
I would like to have a PSIClass that represents this:
public class MyClass<T> { ... }
The goal is to dynamically add methods to such class and eventually write the complete class to a file. The class needs to declare the Type Variable because some methods will receive/return T
Thanks!
I have found a solution in the intelliJ developer forums. It doesn't seem to be the neatest one, but it works.
I'd recommend to use
PsiFileFactory.getInstance(...).createFileFromText("ClassName.java",
JavaFileType.INSTANCE, "class ClassName { ...}"), cast the result
to PsiJavaFile and use its getClasses[0] as the result.
Here is the link to the thread:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/115000089970-Create-a-new-PSIClass-with-Generic-type-parameters?page=1#community_comment_115000122164
I have an antlr4 grammar file that parses a BASIC language. Is there a way to insert more code in my extended baseListener class?
For example, if I am parsing this code:
10 print "hello world"
%include "moreCode.bas"
print "after include"
moreCode.bas could be something like:
for t% = 1% to 10%
print t%
next t%
I need to detect the include command and include the contents into the file being walked and continue walking it as a whole.
So I was thinking that in my enterIncludeCommand method in my listener class I would start a new parser for moreCode.bas and then somehow insert the tokens/contexts into my current one.
What is the correct way of doing this?
There is no one right pattern. That said, one effective way is to have your main initiate the parser by always calling through a constructor that takes a state object and a source path as parameters
public class BasicParser {
public static void main(String[] args) {
...
StateModel state = new StateModel()
RecurseParser rp = new RecurseParser(state, pathname);
...
}
}
public class RecurseParser {
public RecurseParser(StateModel state, String pathname) {
this.state = state;
this.pathname = pathname; // source text to parse
...
}
public StateModel getResults() {
return this.state
}
In your enterIncludeStatement method, create and run a new RecurseParser instance directly. In your exitIncludeStatement, retrieve the new current state and, as appropriate, validate/check for errors.
Since the state model encapsulates your symbol table, etc., you maintain continuity as you walk through the forest -- recursion is effectively free.
Should mention that, relative to the symbol table, treat executing an include essentially the same as calling a subroutine.
Related: Symbol Table
I have two solutions for this and I took the last one I am going to mention. Also GRosenBerg has a great idea too.
1) use the TokenStreamRewriter and in the enterIncludeStatement use the rewriter insertBefore, insertAfter and/or replace methods. At the end of the walk of that particular listener object, call the rewriter getText() and that will give you the combined string. You will have to reparse that text to go the next listener pass.
2) In the enterIncludeStatement method of the listener class, get the include file name, run the lexer/parser on it and then take the first StatementContext(in my case) and inject it into the current tree using the IncludeContext.AddChile(myStatement). Looping for each statement line in that include file. The tricky part is to include the statements in the correct place but you will end up with a complete tree that you can walk with the next listener class phase.
I used option 2 and its working for me so far however I'm not sure using the addChild method is the best way since I am really inserting siblings not children. Given this siblings/childrens issue then maybe grosenberg's recursive idea would be the best.