Passing parameter to class property in Java - java

I have this property in a visual basic class. NET 2008, the property in addition to the get and set has a parameter called "pParam. "
Public Property UpdateField(ByVal pParam As String) As String
Get
Return Me.idField
End Get
Set(ByVal value As String)
Me.idField = value
If pParam = "NEW" Then
// some code here
End If
End Set
End Property
which is the equivalent of this in java code?
to use I do the following:
oClass.UpdateField("NEW") = 1850
I have this code in java
public void setUpdateField(String idField) {
this.idField = idField;
}
public String getUpdateField() {
return idField;
}
but I need to put the parameter "pParam"
Thanks in advance.

What you've got in the .NET code is an indexer in C# terms. There's no equivalent in Java - you'll just need to take two parameters:
public void setUpdateField(String idField, String pParam) {
...
}
Frankly I think it's a little odd that the "getter" in .NET doesn't seem to use the index...

Related

Find all Java methods using only one specific property of a specific type of parameter

We're in the process of trying to identify everywhere that a specific type of object is used only to get a specific property from it, and pass that property into the method instead.
I'm thinking IntelliJ IDEA's "Structural Search" might be a good tool for this, but I'm not sure how to formulate the search template.
A concrete example:
public class MyClass {
public Long getId() {...}
public void setSomethingElse(int se) {...}
}
public class SomeOtherClasses {
public void shouldBeMatched(MyClass mc) {
doSomething();
mc.getId();
doSomethingElse();
}
public void shouldNotBeMatched(MyClass mc) {
doSomething();
mc.getId();
mc.setSomethingElse(14);
doSomethingElse();
}
public void alsoShouldNotBeMatched(MyClass mc) {
shouldBeMatched(mc);
}
}
In the above example, if I'm looking for methods that only use getId, then I should find shouldBeMatched, but not be bothered with shoudNotBeMatched and alsoShouldNotBeMatched, because they do something with the mc object other than call getId().
I'm thinking IntelliJ IDEA's "Structural Search" might be a good tool for this
And it is indeed. The documentation can be tough though.
Let's check Search templates, filters, and script constraints page. It goes as follows.
Let's say, you have a variable that matches a method, a toString()
method. Then this variable is actually a PsiMethod node. Retrieving
variable.parent will produce a PsiClass node, and so forth.
variable.text then will give you the entire text of the method. If you
just need the name of the method, you can use variable.name.
It seems that the task can be done by choosing the right template and writing a corresponding Groovy script.
The template is called methods of the class and can be found under Existing templates. They provide __context__variable to be used with a script.
We have to be sure matched methods have parameters. It is simple enough, just put a count filter on a $Parameter$ variable.
Then we need to extract the name of a parameter of desired type and see if it is called in the body of the method. The following script will do.
def parameters = __context__.getParameterList().getParameters();
def parameter = parameters.find { p -> p.getType().getName().equals('MyClass') };
if (parameter == null) return false;
String parameterName = parameter.getName();
String methodText = __context__.getText();
String occurrence = "${parameterName}.";
String methodCall = "${parameterName}.getId()";
return methodText.count(occurrence) > 0 && methodText.count(occurrence) == methodText.count(methodCall);
Put it in the $Method$ variable filter and verify the results.

Java - Remove "Optional" from a variable (convert)

for a piece of homework, I have to set a variable. The set method given to me, converts that into "Optional". However, I have to store this variable in an ArrayList which doesn't allow Optional variables.How can I convert the variable so it is no longer Optional?
The set method:
public void setParentVertex(IVertex<T> parentVertex)
{
if(parentVertex == null)
this.parentVertex = Optional.empty();
else
this.parentVertex = Optional.of(parentVertex);
}
Where I'm trying to use it:
ArrayList<IVertex<T>> path = new ArrayList<IVertex<T>>();
IVertex<T> parent = current.getLabel().getParentVertex();
path.add(parent);
The error I keep receiving is: "Error: incompatible types: Optional> cannot be converted to IVertex" due to the line where I declare the variable "parent".
Thank you.
Here is the correct version
List<IVertex<T>> path = new ArrayList<IVertex<T>>();
current.getLabel().getParentVertex().ifPresent(path::add)
Also it would be good to rewrite setParentVertex function:
public void setParentVertex(IVertex<T> parentVertex) {
this.parentVertex = Optional.ofNullable(parentVertex);
}
I think you don't have to add it to your list, if there is no value. So just do
if(nameOfOptional.isPresent()){
list.add(nameOfOptional.get());
}
First, add a check to find the value is present or not (by calling isPresent()) and then if the value is present then add to your ArrayList path object as shown below:
ArrayList<IVertex<T>> path = new ArrayList<>();
Optional<IVertex<T>> parent = current.getLabel().getParentVertex();
if(parent.isPresent()) {
path.add(parent.get());
}
or the shorter form is shown below which uses ifPresent method:
ArrayList<IVertex<T>> path = new ArrayList<>();
Optional<IVertex<T>> parent = current.getLabel().getParentVertex();
parent.ifPresent(path::add);
Also, I suggest you have a look at the Optional API methods here.
As a side note, I recommend you to use diamond <> operator while declaring generic types (like shown above i.e., new ArrayList<>()) , so that your code will be less verbose.

I want to implement this format 12345-1234567-1 in regular expression in java

I want to implement a pakistan's standard format of cnic number which is like this:12345-1234567-1.
But I don't know anything about this. I found the following code for this purpose but it also giving errors in NetBeans.
private void idSearchKeyPressed(java.awt.event.KeyEvent evt) {
String cnicValidator = idSearch.getText();
if (cnicValidator.matches("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$")) {
idSearch.setEditable(true);
}
else {
idSearch.setEditable(false);
}
}
The pattern is correct. But it can be condensed to this:
^[\\d]{5}-[\\d]{7}-\\d$
Where does idSearch come from? If its not a final member of the class you can't access it in that way. So make sure idSearch is available inside idSearchKeyPressed. Also make sure that there are no trailing spaces or something like that. You can do this by calling
cnicValidator = cnicValidator.trim();
The following example returns true for both regex versions.
public static void main(String... args){
String id = "35241-7236284-4";
System.out.println(id.matches("^[\\d]{5}-[\\d]{7}-\\d$"));
System.out.println(id.matches("^[0-9+]{5}-[0-9+]{7}-[0-9]{1}$"));
}

How to check Type Ranges with Java development tools (JDT)?

I want to parse a String, which contains a number, using JDT to find out whether the contained number is inside the valid Range of one of the Primitive Types.
Let's say i got a float value like this as String "1.7976931348623157e350" and want to see whether it is still inside the allowed range for primitive type 'double'. (In this case it would not be inside the valid range, because the maximum exponent of double is 308).
I don't want to use the standard methods like : Double.parseDouble("1.7976931348623157e350"), because I'm afraid it might be too slow if I have a big amount of primitive types, which I want to check .
If you know the Eclipse development environment you will know that inside a normal java file, eclipse is able to tell whether a variable is out of range or not, by underlining it red, in the the case of 'out of range'. So basically i want to use this functionality. But as you can guess - it's easier said then done!
I have started experimenting with the ASTParser from this library: org.eclipse.jdt.core.dom
But I must admit I was not very successful here.
First i tried calling some of those vistor methods using methods like:
resolveBinding() , but they always only returned me "Null".
I have found some interesting class called ASTSyntaxErrorPropagator , but i'm not sure how this is used correctly. It seems to propagate parsing problems or something like that and gets it's information delivered by some thing class called CodeSnippetParsingUtil I assume. Anyways, these are only speculations.
Does anyone know how to use this ASTParser correctly?
I would be really thankful for some advice.
Here is some basic code-snipped which I tried to debug:
public class DatatypesParser {
public static void main(String[] args) {
ASTParser parser = ASTParser.newParser(AST.JLS4);
Map options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_7, options);
String statement = new String("int i = " + Long.MAX_VALUE + ";");
parser.setSource(statement.toCharArray());
parser.setKind(ASTParser.K_STATEMENTS);
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
ASTNode ast = parser.createAST(null);
ast.accept(new ASTVisitor() {
#Override
public boolean visit(VariableDeclarationStatement node) {
CodeSnippetParsingUtil util = new CodeSnippetParsingUtil();
return true;
}
});
}
I don't want to use the standard methods like :
Double.parseDouble("1.7976931348623157e350"), because i'm afraid it
might be too slow if i have a big amount of primitive types, which i
want to check .
Under the hood JDT is actually using the standard methods of Double to parse the value, and quite a bit more - so you should always use the standard methods if performance is a concern.
Here is how the double gets parsed by JDT.
From org.eclipse.jdt.internal.compiler.ast.DoubleLiteral:
public void computeConstant() {
Double computedValue;
[...]
try {
computedValue = Double.valueOf(String.valueOf(this.source));
} catch (NumberFormatException e) {
[...]
return;
}
final double doubleValue = computedValue.doubleValue();
if (doubleValue > Double.MAX_VALUE) {
// error: the number is too large to represent
return;
}
[...]
}

what is Java best practice to handle enum's

hi I know Java for a long time and recently I have been diving deep to the Java world.
As an experienced c# developer I find it odd to use Java enum's.
For example if I show on console items such as :
public enum AdminOpertionFirstlayer
{MANAGE_SUPPLY,
MANAGE_CUSTOMERS_SERVICE,
ORDERS_MANAGEMENT,
REPORTING_OPRATIONES}
I find it hard to write them down to the user , cause I have to define new varible
*AdminOpertionFirstlayer []adminOpertionFirstlayerArr =
AdminOpertionFirstlayer.values();
in order to achieve this :
for (int i = 0; i < adminOpertionFirstlayerArr.length; i++) {
String s = String.format("%d. %s",
i+1,
adminOpertionFirstlayerArr[i].toString());
Screen.print(s);
}
AdminOpertionFirstlayer chosen= adminOpertionFirstlayerArr
[(Integer.parseInt(dataIn.readLine()))-1];
But I feel it's a bad practice to declare on *
Is there a best practice (enum extension is one ... ) ?
Is there TryParse available or every time I parse I should try and catch ?
thank you
EDIT
does doing this is understandable and readable ?
public enum MainMenuOptiones{
ADMIN {public void secondLayerMenu(){
Main.AdminSecondLayerMenu();}},
CUSTOMER{public void secondLayerMenu(){
Main.customerSecondLayerMenu();}},
EXIT{public void secondLayerMenu(){
System.exit(1);}},
UNAPPLICABLE{public void secondLayerMenu(){
Screen.printToScreen("chice doesnt exist try again");}};
abstract public void secondLayerMenu();
}
the phrphes is instead of using all the switch mechanism
I can use
enumInstance.secondLayerMenu();
You could use Java's enhanced for loop (and the ordinal value for the enum)
for (AdminOperatorFirstLayer operator : AdminOperatorFirstLayer.values()) {
String s = String.format("%d. %s", operator.ordinal(), operator);
Screen.print(s);
}
Then you can use the ordinal value to recreate the enum:
AdminOperatorFirstLayer chosen =
AdminOperatorFirstLayer.values()[(Integer.parseInt(dataIn.readLine()))];
Or you could use the name:
for (AdminOperatorFirstLayer operator : AdminOperatorFirstLayer.values()) {
String s = String.format("%s. %s", operator.name(), operator);
Screen.print(s);
}
Then you can use valueOf value to recreate the enum:
AdminOperatorFirstLayer chosen =
AdminOperatorFirstLayer.valueOf(dataIn.readLine()];
The Enum<E> class is the base for all enums in Java.
There's no need to declare a variable with values, use an enhanced for loop to print them out if you want the users to read your source code.
Generally you want to print out a localised string rather than the name of the enum in the source.
There isn't an equivalent to TryParse, instead use AdminOpertionFirstlayer.valueOf(AdminOpertionFirstlayer.class, string) and catch the IllegalArgumentException.

Categories