I am trying to get the constructor of a variable by using an ASTVisitor.
public boolean visit(VariableDeclarationFragment node)
{
IVariableBinding variableBinding = node.resolveBinding();
// I can't seem to get the constructor here
}
SAMPLE
Base b = new Derived(); // How do I get packageNAME.Derived?
int x = 5; // How do I get 5?
You need to look deeper into the syntax tree to find the answers. The ASTView is a great help in cases like this. This is the update site I use with Kepler: http://www.eclipse.org/jdt/ui/update-site
Your Samples could be answered like this (simplyfied):
/*
* Base b = new Derived(); // How do I get packageNAME.Derived?
*/
private String getClassNameFromConstructor(VariableDeclarationFragment fragment) {
Expression initializer = fragment.getInitializer();
if (initializer instanceof ClassInstanceCreation) {
ClassInstanceCreation instanceCreation = (ClassInstanceCreation)initializer;
if (instanceCreation.getType() instanceof SimpleType) {
SimpleType simpleType = (SimpleType)instanceCreation.getType();
return simpleType.getName().getFullyQualifiedName();
}
}
return null;
}
/*
* int x = 5; // How do I get 5?
*/
private String getInitialisationNumber(VariableDeclarationFragment fragment) {
Expression initializer = fragment.getInitializer();
if (initializer instanceof NumberLiteral) {
NumberLiteral numberLiteral = (NumberLiteral)initializer;
return numberLiteral.getToken();
}
return null;
}
Variables don't have constructors. Objects have constructors. Find the assignment, find the expression being assigned, and if that expression is a constructor you can get the class name from that.
Related
I have a script provided from the client like this
segment-id Integer
segment-description String
Now I want to build a class with the following methods
Sample sample = new Sample();
// casting to the type specified in the script
(map.get("segment-id")) segmentId = sample.get("segment-id");
// Now it can be used as an Integer
Integer result = segmentId + 2;
Is it possible to do something like
Class<map.get("segment-id")> segmentId = new Class<map.get("segment-id")>();
Or any better solution...? I need a way create objects of specific type, which I don't know in advance.
My current solution is
public Integer getInteger(String key) {
return map.get(key);
}
but in this way I have to know in advanced segment-id is of type Integer.
You can use Class.forName() to get the class and .newInstance() to get a new instance:
Object createdObject = Class.forName("java.lang.String").newInstance();
or ...
Object createdObject = Class.forName("java.lang.Integer").newInstance();
If you need to know if it's a String:
if(createdObject instanceof String) {
String castValue = (String) createdObject;
...
}
if(createdObject instanceof Integer) {
Integer castValue = (Integer) createdObject;
...
}
But you could just test the incoming string:
if("java.lang.String".equals(nameOfClassToCreate)) {
....
}
I am using a recycler view to display data on my app. When I want to get the information from an API that I am using I am taking in 14 different variables.
for(int i = 0; i<array.length();i++){
JSONObject object = array.getJSONObject(i);
//object.getJSONObject("test");
Personnel personnel = new Personnel(
object.getInt("contactType"),
object.getString("currentTime"),
object.getString("clockIn"),
object.getString("clockOut"),
object.getInt("isClockedIn"),
object.getString("clockInPhotoName"),
object.getDouble("clockInLat"),
object.getDouble("clockInLng"),
object.getDouble("clockOutLat"),
object.getDouble("clockOutLng"),
object.getDouble("projectSiteLat"),
object.getDouble("projectSiteLng"),
object.getDouble("clockInDistanceFromProjectSiteInMetres"),
object.getDouble("clockOutDistanceFromProjectSiteInMetres")
);
personnelList.add(personnel);
}
But in my response body from my http call, some times for example, the object that is calling "isClockedIn", may be empty, and if I do this, then my constructor wont make an object.
This is my very long constructor:
public Personnel(int contactType, String totalTimeSummary, String clockInTime, String clockOutTime, int isClockedIn, String clockInPhotoName, double clockInLat, double clockInLong, double clockOutLat, double clockOutLong, double projectLat, double projectLong, double clockInDistance, double clockOutDistance) {
this.contactType = contactType;
this.totalTimeSummary = totalTimeSummary;
this.clockInTime = clockInTime;
this.clockOutTime = clockOutTime;
this.isClockedIn = isClockedIn;
this.clockInPhotoName = clockInPhotoName;
this.clockInLat = clockInLat;
this.clockInLong = clockInLong;
this.clockOutLat = clockOutLat;
this.clockOutLong = clockOutLong;
this.projectLat = projectLat;
this.projectLong = projectLong;
this.clockInDistance = clockInDistance;
this.clockOutDistance = clockOutDistance;
}
I was looking around and saw that you can just make a default constructor if my other constructor doesn't fill all the needed variables, but of course I dont want to do this because then all of the parameters will be empty.
Cheers.
Instead of calling getDouble, you can use optDouble. The first value should be the key you're already using, the second value should be the value that will be used whenever the key is not found from the server response.
You can find some real world examples here: https://www.programcreek.com/java-api-examples/?class=org.json.JSONObject&method=optDouble
You should not use primitive variables. For example, int can't be null, On the other hand integer type can be null. Take a look at this link
As GhostCat suggested, you should really consider builder pattern, example:
public Personnel {
public static class Builder {
int contactType;
//all the other members
public Builder contactType(int contactType) {
this.contactType = contactType;
return this;
}
public Personnel build() {
Personnel personnel = new Personnel();
personnel.contactType = this.contactType;
}
}
int contactType;
//all the other members
private Personnel() {}
// getters and setters
}
Personnel personnel = new Personnel.Builder()
.contactType(0)
.build();
I have a class function in java code. I would like to make a class function in matlab that works similar with class function java. Could you help me to change it
This is my java code
public class Return{
byte m[][];
int indcs[];
public Return(byte T[][], int ind[])
{
this.m=T;
this.indcs=ind;
}
public byte[][] getfirst(){
return m;
}
public int[] getsecond(){
return indcs;
}
}
You could try the following (note that it does not check variable type):
classdef Ret
properties (Access = public)
m = []
indcs = []
end
methods (Access = public)
function obj = Ret(T, ind)
obj.m = T;
obj.indcs = ind;
end
function x = getfirst(obj)
x = obj.m;
end
function x = getsecond(obj)
x = obj.indcs;
end
end
end
You don't have to use the (Access = public) - all properties and methods are public by default.
I encountered a problem while dealing with a call of a static method in another class.
So I have a function which is like follow, where I need to extract two values, a counter and an object :
public static int getEarliestValue(Map<DBObject, DBCursor> cursorMap, DBObject result) {
int mergeCount = 1;
if (!cursorMap.isEmpty()) {
long ealiest = Long.MAX_VALUE;
for (DBObject o : cursorMap.keySet()) {
// do stuff to init tmp
...
if (tmp < ealiest) {
result = o;
ealiest = tmp;
}
// other stuff .....
}
return mergeCount;
}
here is how I call it in my other class :
DBObject result= null;
int mergeCount = MongoTickReaderUtil.getEarliestValue(cursorList, result);
I checked in debug mod and result is set in getEarliestValue but when it's go out of the function call result is still null.
I thought that references where like pointers with the difference that we couldn't do arithmetic operation on the reference itself, but with this behavior it seems that even if we change the pointed value it still only in the local scope.
The only idea that I found was to put it in a List but this is neither elegant nor optimal.
Any suggestion ? Thanks in advance.
Passing result here is the same thing as passing null. You have to return this DBObject someway. For example, you can return something like Map.Entry<Integer, DBObject>. This could not be supposed to be a good solution, maybe you should create some class like BlahBlahResult, containing both int result and DBObject.
If you really-really want to pass it as a parameter, you may pass something like AtomicReference<DBObject> and set it inside the method:
public static int getEarliestValue(Map<DBObject, DBCursor> cursorMap, AtomicReference<DBObject> result) {
int mergeCount = 1;
if (!cursorMap.isEmpty()) {
long ealiest = Long.MAX_VALUE;
for (DBObject o : cursorMap.keySet()) {
// do stuff to init tmp
...
if (tmp < ealiest) {
result.set(o);
ealiest = tmp;
}
// other stuff .....
}
return mergeCount;
}
...
...
AtomicReference<DBObject> resultReference = new AtomicReference<>(null);
int mergeCount = MongoTickReaderUtil.getEarliestValue(cursorList, resultReference);
DBObject result = resultReference.get();
In java "References to Objects are passed by value".
DBObject result= null;
int mergeCount = MongoTickReaderUtil.getEarliestValue(cursorList, result); // here result --> null i.e, points to nothing
public static int getEarliestValue(Map<DBObject, DBCursor> cursorMap, DBObject result) {
int mergeCount = 1;
if (!cursorMap.isEmpty()) {
long ealiest = Long.MAX_VALUE;
for (DBObject o : cursorMap.keySet()) {
// do stuff to init tmp
...
if (tmp < ealiest) {
result = o; // here (new)result --> o . (original)result-->null
ealiest = tmp;
}
// other stuff .....
}
return mergeCount;
}
the result parameter is a pointer. Java does not support pointer-to-pointer as in c/c++.
you can use a class contains a DBObject field, then pass this class to the method.
class Dummy {
DBObject result;
}
modify your getEarliestValue method, replace the argument DBObject result with Dummy dummy,
public static int getEarliestValue(Map<DBObject, DBCursor> cursorMap, Dummy dummy)
and then replace code result = o with dummy.result = o
Dummy dummy = new Dummy();
int mergeCount = MongoTickReaderUtil.getEarliestValue(cursorList, dummy);
DBObject result = dummy.result;
this is a simulation of **ptr in c/c++
You can do the following:
DBObject result= new DBOBject() // or any initializing code;
/** don't try to change or re-initialize reference inside the method
because the result will still point to old one
*/
int mergeCount = MongoTickReaderUtil.getEarliestValue(cursorList, result);
// use the result reference.
This is not specific for java also in the C++ or C pointer unless you use the & with pointer reference.
Note that it seems that the method cann't run alone with out DBObject instance so I think this method should be an instance method of Class DBObject and not a Util method,
For example:
int mergeCount = result.getEarliestValue(cursorList);
I am passing few values to mail method for sending the details like below
private static String getTeam(String Team, List<String> prioritys1, String number,String description
) {
StringBuilder builder1 = new StringBuilder();
for (String v : prioritys1) {
if ( v == "1") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
else
if ( v == "3") {
Integer cnt1 = count1.get(new Team(Team, v,number,description));
if (cnt1 == null) {
cnt1 = 0;
}
else
if (cnt1 !=0){
cnt1 = 1;
mail1(Team,v,number,description);
}}
}
return builder1.toString();
}
I tried to store in arrays but it didnt worked.
I after pass above parameters, i need to store the value of the number. i need to store the number so that next time while passing the parameters i need to check first whether the number is already passed or not if not then only i need to pass to mail.
can any one help on this
With this code very complicated understand what you are doing. But if you need check value that already been processed store it outside of the method. Create global class variable:
public class className {
private final List<String> ARRAY = new ArrayList<>(); // global variable
public void yourMethod(String value) {
if (!ARRAY.contains(value)) {
mail(value);
ARRAY.add(value);
}
}
}
I dont know your case and I can not get better example.
You need to store the value in a "class level" variable. Whether the variable type needs to be static or instance will depend on your implementation of the method.
If you can post a sample code, we can help further.
You need to compare with 2 equals and not 1
Instead of
if( Team = A )
you need this way
if( Team == A )
Using Team = A, your saying that every time your code reaches that line it will equal Team to A.