how to get local variables of a method from another class - java

I have two classes A and B
A class contains a method which has some of the local variables.
now I want to fetch a particular variable's data type in the B class.
can you please help me with this.
I researched about java reflection. but I found that I can not achieve this by using reflection, as local variables are stored in stack at the runtime. And reflection can only fetch instance or class variables.
for example,
class A{
method1(){
variable1;
}
}
class B{
method 2(){
fetch variable1;
}
}
I want the data type of variable1 as a result.
Is there any way to achieve it using mocking or something?

thanks for your support.
I found the answer myself.
I can do this via Java Regex Concept.
As I know a little about the variable's naming pattern,
So I am planning to parse the class1.java file and first will try pattern matching the method name and then the variables name.
So that I will get the line on which the variable is declared.
for example, if my variable is object,
String abc=new String();
I will try regex like, String regex=".=new.().*"
So this will fulfill my purpose.
Thanks again for helping.

Related

Getting a variable using a variable

How would I get a variable in another class using a variable in the current class? For example: The variable "userclass" Can either be human or alien. Inside my other class ("Cv.java") there are two variables (human, alien) How would I get one of the two variables in Cv.java, while using the "userclass" variable to get it.
Example 2:
userclass = alien
Cv.????
How would I get Cv.alien whilst using "userclass"
You can use reflection to do it, although it might hurt the performance.
A better way is to use a Enum to represent the userclass instead of using a String.
how about using class.forName :
Object o = Class.forName(userclass)
this assuming your userclass is a string.

Instantiate a Java object through reflection

I have a question regarding a specific way of instantiating a Java object.
Basically, I need to implement a Singleton which implements an interface. I currently try to use a factory and a bit of reflection to do this, trying to reproduce this example (5th post, precisely).
The part that I like is that through this method, I can change the Singleton's implementation quite easily.
The problem is that I don't really understand how to retrieve the Class name. In the example above, the System.getProperty() seems to be a way to do this, but the example doesn't show precisely all the types needed to do this (the field isn't typed). The problem is that I don't know which key to give to the getProperty() method. It seems that it must be the singleton private static field's name with .type (i.e. mySingleton.name), but it doesn't seem to work...
I would like to know how can I retrieve the class name.
By the way, if there's a better way to do this, I'm open to suggestions.
typeName is String . So what you need is Fully Qualified Class Name to load the class with reflection like you
Class type = Class.forName(typeName);
System.getProperty() is a way to access the system properties/ environment properties that you have at the time of executing the program.
To narrow it down for you with an example you can set the system varible like below :
If in windows :
cmd> set a.type = mytest.testclass
If in linux :
$ export a.type = mytest.testclass
Make your the class that you are try to load is in classpath.
The above steps you need to perform before running your program.
Coming to best practices, the above approach can be used to test programs but when going into real time solutions you probably will have some way to read these class name from a file or database. Probably some kind of configuration parameter.
If you are asking about String typeName = System.getProperty("a.type"); in"
private synchronized static final void createA()
{
// This is just one possibility for getting the class name.
String typeName = System.getProperty("a.type");
Class type = Class.forName(typeName);
a = type.newInstance();
}
Where does a.type come from? - it's just System property, declared in your Operating system for this purpose only.
Class c = Class.forName("java.lang.String");
as shown above - Class.forName() requires fully qualified name of class - with package declaration
You can make the property anything you want. You can get the properties with System.getProperty("my.property") and you can turn this into a class with Class.forName()
Perhaps you could say what didn't work for you as its all pretty simple and I assume you are doing almost the right thing.

java static keyword

I know the definition of static which is a keyword to refer a variable or method to the class itself. Could this mean if I wrote a method called parseInt() in a class called calculator and another method called parseInt() in a different class called mathProgram, the compiler Eclipse will know which class the method parseInt() is referring to?
You need to call static methods by referencing the class it is a part of:
MathProgram.parseInt();
Is not the same as
Calculator.parseInt();
So written this way it is clear to the JVM which method you were referring to.
Edit: You can also call static methods using an instance variable but this is in bad form and should be avoided. See this SO answer for more info.
Edit2: Here's a link to the Java Coding Conventions section regarding the use of calling static methods from instance variables. (Thanks to Ray Toal for the link left in the answer to a question posted here)
Yes, because static methods and variables must be in a class and to call them outside of that class you need to qualify them.
For example Calculator.parseInt() and OtherClass.parseInt().
Eclipse uses that to tell them apart.
If the method is static, you need to call it using the classname:
Calculator.parseInt();
Otherwise, with an instance:
Calculator c = new Calculator();
c.parseInt();
Either way, its explicit which you want.

In java, what's the relationship between field and class?

Please refer to this API. The link is:
http://download.carrot2.org/stable/javadoc/org/carrot2/text/preprocessing/pipeline/CompletePreprocessingPipeline.html
Class CompletePreprocessingPipeline
Field Summary
DocumentAssigner documentAssigner
Document assigner used by the algorithm, contains bindable attributes.
Then I found some example using completePreprocessingPipeline this way
completePreprocessingPipeline().documentAssigner()exactPhraseAssignment(true)
I do not understand the relationship between "completePreprocessingPipeline" and "documentAssigner" in terms of "field vs.class".
A class contains fields. All instance of that class have those fields.
http://download.oracle.com/javase/tutorial/java/javaOO/classes.html
In the first example, The Bicycle class has three fields cadence, dear and speed.
This is standard Java code structure, nothing special about it. I suggest you learn some Java and the Javadocs may make more sense.
Your example must be from some other language. Maybe a scripting language that can run on the JVM or see Java libraries.
What might be true in java:
CompletePreprocessingPipeline completePreprocessingPipeline = new CompletePreprocessingPipeline();
completePreprocessingPipeline.documentAssigner.exactPhraseAssignment = true;
You instantiate a class, and get an object. Then you can refer to fields in the object, if the field modifier allows it (if it were public for example)
A field is a member variable of a class. The type of the field may indeed be another class.
In this case their appears to be a "getter method" .documentAssigner() which returns the documentAssigner field, which is of the type DocumentAssigner.
I do not understand the relationship
between
"completePreprocessingPipeline" and
"documentAssigner" in terms of "field
vs.class".
That's because your question doesn't make sense. Both completePreprocessingPipeline() and documentAssigner() are methods. No fields at all in that code. Ad there is a missing '.'.

why we use set method [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the point of setters and getters in java?
I have a question about set method. Please provide some details if possible.
I want to know why do we use set method with class name.
public class Mymainclass {
Private class ClassC {
Private Mysecondclass sec = null;
public void setMymainclass(Mysecondclass second){
Mymainclass.sec= second;
}
}
}
Is it just setting the sec variable value ? if yes why there is class name with set?
It seems like you are confusing a "class constructor" with a "setter method" in a class.
The primary reason for a constructor is to intialize the class variables
The primary reason for a setter method is to access private variables inside the clas
So in your case the name of the method should be "setSec" rather than setMainClass.
That is if you would like to modify the private variable "sec" after you have initialized the class then you can choose to use a setter method.
On the other hand you can also not use a setter method and just have the sec variable be initialized when the class is first created. To do that you will have to create a constructor.
Your constructor for this class will look like this:
Mymainclass(Mysecondclass sec){
this.sec = sec;
}
This way you can pass is a Mysecondclass object as soon as you create a new instance of Mymainclass.
Also try to make sure when you label classes to make each word in the class name to have its first letter capital like this: MySecondClass and MyMainClass!!
Firstly your method should be called "setSeconds" if you follow good practice. Just think how confusing it would be if you added a minutes member to your class.
There are two main reasons for coding setters and getters.
The first is purly pragmatic. If you want to invoke the magic of introspection and java beans then you need to follow these conventions. There are several libraries/APIs like FreeMarker that absolutly depend on haveing getter and setter methods in your class.
The second has more to do with good design. Consider thet you have a public member called seconds. Any user of you class could set this by coding.
instanceOfYourClass.seconds = 60;
This is just fine except maybe you want to impose an arbitary limit of 42 seconds on this value. To validate the value and set it a max of 42 seconds you now need a method to do this. So every user of you class must now change thier code to:-
instanceOfYourClass.setSeconds(60);
So by building in getters and setters from the start you are building in both the flexibilty to do more exotic things within your class, while at the same time providing a stable interface to your class users which wont rquire them to change thier code every time there is a small change in functionality.
I think part of the source of your confusion is that the example you gave is bad code! You don't name a setter based on the class of its argument, you named it based on the property of the object that you're setting. e.g., the canonically 'correct' version of your example would be:
public class Mymainclass {
private Mysecondclass sec= null;
public void setSec(Mysecondclass second){
this.sec= second;
}
}
Having setters that map to property names allows all kinds of different frameworks from UI to persistence and all in between to manipulate your objects in an abstract way. If you tell, for example, your database layer that the property named 'sec' maps to a particular database column, it can use reflection to find the method named "setSec" and set it for you!
The idea of having lots of methods just named 'set' also breaks down when you have lots of properties of the same type, lots of Strings, lots of BigDecimals, whatever. It would be really wierd if there were two standards to only use 'set' when you can and use the property name when you have to. (and you'd find yourself refactoring away those 'set' only methods awfully often.)
In object oriented programming, a good practice is to expose getters and setters to allow other class to interact with a class content instead of making member variables public.
Even if most of the time, at least in the very first version of the class, there won't be much more there than the actual assignment statement, this will allow you to add other behaviors later:
add logging traces to know when and how a new value has been set
do some controls/transformations on the value that is passed before really assign it (what if the other class provided null ?)
trigger some other actions that could be necessary whent this new assignment is done
...

Categories

Resources