How do I search through source code to find and remove all uses of 'this' for example:
'this.getVersion()' would change into 'getVersion()'
I figure I need a regex, but I don't know how to create one to search the code for it.
Thanks.
I would advice against that. Because say you have a method
public class Foo {
private int a;
public void Bar (int a) {
this.a = a;
}
}
By removing this., the semantics of the method are altered.
You cannot modify this semantic-safe without building a parse-tree and doing some semantical analysis.
If you really wish to proceed:
\bthis\.
Is a regex that will probably do the trick.
A regex could work, to match words containing "this" (say, (.*)(this)(.*))
But without more semantic information, you could be removing random this's. Ever worse, you might change the meaning of the code. Why do you want to do this?
I am assuming you want to write this in Java, and that you have read the cautionary note in the other answer. You can just load each file into a String and use
myFileString.replaceAll("\\bthis\\.", "");
See the Javadoc for details.
Related
I am wondering what would be a regular expression that would detect any function declaration which has a body containing a call to itself in Java.
Example of a method that would match:
public int method()
{*n
method();
}*n
Thank you for any help.
Consider the following code samples:
public int method() {
System.out.prontln("method() started");
}
or
public int method() {
// this method() is just an example
}
Do you see now that you need a full-blown parser?
I don't see how this could be done reliably with a regular expression, since the arguments to any method call could be arbitrarily complex, and even include anyonymous classes containing similarly named methods.
So, the answer is "no"; at least not if you want it to be reliable.
This is a quick and dirty example. It would lead to many false positives and generally be slow. It doesn't take into account curly brackets and strings which could contain curlies. However, it works for your input. :-)
Matcher m = Pattern.compile("([\\w\\d_$]+\\s*\\([^)]*\\))[^{]*\\{.*\\1[^}]+}", Pattern.DOTALL |Pattern.MULTILINE).matcher(s1);
System.out.println(m.matches());
I'm making a command-line based tool in Java, and I was thinking I might be able to make it all a bit easier on my self if I could take user input and automatically find the needed functions based on the users input.
What I want to do, is, that if a user types:
User create newUser
The java code looks for a class called user, then looks for a function called create, and inputs newUser as the first argument of the function. Meaning typing the command "User create newUser" would make the java code trigger this line of code:
User.create("newUser");
And of cause, return errors if the class or function was not found, or so.
So far I've been playing with
Class.forName(cmdArg[0])
Where cmdArg[0] is the first word given by the Scanner, found by splitting where there's spaces.
Anyway, is it possible to achieve this in Java? Any help would be much appreciated.
My solution:
Okay, i got it working, my final solution was a combination of duffymo's and user978548's answer, my solution looks like this:
Class comArgs[] = new Class[1];
comArgs[0] = String.class;
String[] args = new String[1];
args[0] = commandArray[2];
Class.forName("code."+commandArray[0])
.getDeclaredMethod(commandArray[1], comArgs)
.invoke(null, args);
This is surrounded by a try/catch with allot of exceptions, but it works.
I also have a HashMap for which commands i want to receive.
The args variable can should be as long as the number of arguments needed for the called method.
You can use the features built into the java.lang.Class class:
Class.forName(args[0]).newInstance();
Have your users input the fully-resolved class name and you don't have to worry about all those shenanigans. You'll need them anyway, because the short name might not be unique.
Another approach is to put the Class instances that you want users to be able to create in a Map and have them input the key.
as duffymo said, Class.forName(args[0]).newInstance(); for the class, and as Chin Boon said, you have all that you want in reflections method. Like, to run your method:
Object.class.getMethods()[find your method here].invoke(obj, args)
What you are looking for is Java reflection.
duffymo is correct - reflection is what you are prob talking about.
However, I would maybe suggest looking at a combination of Builder/Factory design patterns to make this a little nicer rather than using reflection to attempt to find the class/methods you want (although obviously this depends on the context of the problem and I am making some assumptions here!).
I just want to know that is it possible in java to use
class{
private final static String AND="&&";
public static void main(String...args)
{
String str="subodh";
if(str!=null AND str.equals("subodh") )
{
System.out.println(str);
}
}
}
The above is not allowed but is there any such kind of way through we can use it by putting some extra efforts if it's please let me know or please put your openions.
Thanks
No, there's no way of changing the operators in Java - thankfully, IMO.
I suggest you learn to use Java as Java rather than trying to make it look like some other language. (Or use that other language which looks more like you want it to.)
If you're trying to do something other than bend the language to your personal preferences, please edit the question to explain what your purpose is.
No, There is no any way to use this. For that I have to go through different language.
No way to make this possible. && is operator and you cannot assign an operator to a String variable. Here AND acts like a String variable.I hope you will get it.I also do not think one will need anything like this in any situation. If possible make your motive clear why you want to this?
If you really wanted to you can implement a class to "prettify" logical operations using method chaining . And then use it something like:
PrettifyLogic.condition(str!=null).and(str.equals("subodh")).evaluate();
Though I don't personally find that more appealing to read/write. Also, good luck with operator precedence if you try something like this!
Nope, Java doesn't support doing this type of thing and I'm thankful for that! If it did we could get all sorts of things meaning && which would make existing code hard to read.
If you want to code in Java, you'll just have to stick with the way Java does things.
In Python/C++, I normally use _("string") for i18n string text.
for Java, I use bundle.getString("string"). Obviously, it is uglier than Python/C++.
How to write such code shorter?
Create your own method:
public String _(String key){
return bundle.getString(key);
}
Or something similar. Underscore is a valid method name in Java. Of course, you can use any other single character, if you prefer, say l like localize.
So, now you can call it the same way as in Python.
Thats the way Java is, you can call it ugly, though.
I would pretty much stick with the Java convention and use the bundle.getString(...) version. :)
I like using question mark at the end of method/function names in other languages. Java doesn't let me do this. As a workaround how else can I name boolean returning methods in Java? Using an is, has, should, can in the front of a method sound okay for some cases. Is there a better way to name such methods?
For e.g. createFreshSnapshot?
The convention is to ask a question in the name.
Here are a few examples that can be found in the JDK:
isEmpty()
hasChildren()
That way, the names are read like they would have a question mark on the end.
Is the Collection empty?
Does this Node have children?
And, then, true means yes, and false means no.
Or, you could read it like an assertion:
The Collection is empty.
The node has children
Note:
Sometimes you may want to name a method something like createFreshSnapshot?. Without the question mark, the name implies that the method should be creating a snapshot, instead of checking to see if one is required.
In this case you should rethink what you are actually asking. Something like isSnapshotExpired is a much better name, and conveys what the method will tell you when it is called. Following a pattern like this can also help keep more of your functions pure and without side effects.
If you do a Google Search for isEmpty() in the Java API, you get lots of results.
If you wish your class to be compatible with the Java Beans specification, so that tools utilizing reflection (e.g. JavaBuilders, JGoodies Binding) can recognize boolean getters, either use getXXXX() or isXXXX() as a method name. From the Java Beans spec:
8.3.2 Boolean properties
In addition, for boolean properties, we allow a getter method to match the pattern:
public boolean is<PropertyName>();
This “is<PropertyName>” method may be provided instead of a “get<PropertyName>” method, or it may be provided in addition to a “get<PropertyName>” method. In either case, if the “is<PropertyName>” method is present for a boolean property then we will use the “is<PropertyName>” method to read the property value. An example boolean property might be:
public boolean isMarsupial();
public void setMarsupial(boolean m);
I want to post this link as it may help further for peeps checking this answer and looking for more java style convention
Java Programming Style Guidelines
Item "2.13 is prefix should be used for boolean variables and methods." is specifically relevant and suggests the is prefix.
The style guide goes on to suggest:
There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:
boolean hasLicense();
boolean canEvaluate();
boolean shouldAbort = false;
If you follow the Guidelines I believe the appropriate method would be named:
shouldCreateFreshSnapshot()
For methods which may fail, that is you specify boolean as return type, I would use the prefix try:
if (tryCreateFreshSnapshot())
{
// ...
}
For all other cases use prefixes like is.. has.. was.. can.. allows.. ..
Standard is use is or has as a prefix. For example isValid, hasChildren.
is is the one I've come across more than any other. Whatever makes sense in the current situation is the best option though.
I want to point a different view on this general naming convention, e.g.:
see java.util.Set: boolean add(E e)
where the rationale is:
do some processing then report whether it succeeded or not.
While the return is indeed a boolean the method's name should point the processing to complete instead of the result type (boolean for this example).
Your createFreshSnapshot example seems for me more related to this point of view because seems to mean this: create a fresh-snapshot then report whether the create-operation succeeded. Considering this reasoning the name createFreshSnapshot seems to be the best one for your situation.