How to get number of methods and variables in a class Swift iOS like reflection in Java. Something like getDeclaredMethods() and getDeclaredFields().
getDeclaredMethods() //will return array of methods defined.
getDeclaredFields() //will return array of variables defined.
You use the Mirror(reflecting: Any)and then loop through the mirror.children
This however wont tell you any information about the functions inside it. the child only contains the variable names and values.
i guess This will be a sufficient answer tho.
Related
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.
This question already has answers here:
Java Conventions: use getters/setters WITHIN the class?
(11 answers)
Closed 6 years ago.
Suppose I have a class Circle with a data member float radius. I have a getter and setter method as getRadius() and setRadius(float r). I use the latter to assign the radius value. Now, after the assignment, should I use the value of radius in calculations (in a method called areaCircle()) by directly accessing it or should I call the getter method instead?
You can just use radius as it's defined within the same class. Get and set methods are for getting or setting a variable from another class/object.
You can, and really, you ought to use the class field radius directly.
Having "getters" and "setters" by rote achieves little more than code bloat and a defeat of encapsulation. It's also makes your code less thread safe: what happens if one thread is computing the area while another is changing the radius through the "setter"? It can even, on occasions, be harmful: a child class might override the "getter" or "setter"; remember that all non-static functions are "virtual" in Java.
It's far better is to set all your fields in a constructor, and provide a "getter" if you really must.
And we're no longer in the 1970s. Stop using float. It's probably slower than a double due to internal conversions to and from the latter.
It depends on whether or not you have declared radius private. If you use getters and setters to access it you should have declared radius private because else the encapsulation is broken.
an exception to this might be when the method "areaCircle()" you mentioned is in the same class, in that case it will be able directly access the private radius attribute without the need for using getters and setters.
FYI:
http://www.tutorialspoint.com/java/java_encapsulation.htm
If your value may vary overtime (for example a timer) then use the getter.
If exists getters and setters, then should be used always even inside class. Of course if getter and setter do something more in method then it must be considered if it fullfils Your needs.
Should be used not means must be used. You can use property radius directly ( only inside class if property is private - and should be ) but in good practice is to use getter and setter.
So using property directly is possible, but I recommend use get and set because it give more flexibility and can do something more than tipical assign or get.
For example if in first place setter only sets something, but after a while setter is changed to do something more.
setName(name){
this.name="name";
}
So in code setName("John"); is equal name="John". But imagine that after a while we want to set another property when name is set:
setName(name){
this.name="name";
this.nameIsSet=true;
}
another example ( Listener pattern ):
setName(name){
this.name="name";
this.listener.nameChanged(this.name); //we call listener that variable changed
}
Then programmer needs to find every assigment like name="John" in class and refactor it to new behavior. If only setName is used then no code change must be done.
Of course everything depends from need and is possible that setting, getting property from outside do something more and different and it not fullfils our need inside class.
If you create a private method you can use the radius without getters or setters, but in public mehtodes it's better to use getters and setters.
If it's possible i would use getters and setters. These are better and you will get as less errors as without them.
I am trying to convert some Java to C# and I have a line as follows:
int[][] variableName = get();
What my question is is what does "get();" actually do? There is no function or method in the Java code I am converting called "get()" so I am assuming "get();" simply creates an empty object of the required type, in this case, an empty int[][]. Would I be correct in this assumption or does "get()" in Java have some other meaning?
I have searched for "get()" within stackoverflow but the () are ignored and as a result I get masses of information about HTTP GET which is not what I'm after so excuse me if this is duplicated anywhere else.
All help appreciated.
There is no function or method in the Java code I am converting called "get()"
There must be, either in that class or one of its superclasses, or as a static import although that's not very likely. (Nice one, Jesper!) My guess is that you haven't checked all of the superclasses.
...so I am assuming "get();" simply creates an empty object of the required type, in this case, an empty int[][]. Would I be correct in this assumption or does "get()" in Java have some other meaning?
No, unlike C#, get is not a keyword and has no special meaning in Java. That line of code calls a method called get (it could just as easily be called foo) which is declared in the class or one of its superclasses. It may be a static or instance method, but it will be defined by the class or one of its superclasses, or as a static import.
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.
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
...