From the start of java studying we now have been taught concerning the scope of personal fields/strategies in java however regardless of the actual fact about personal fields/strategies accessibility exterior the category, its achievable utilizing java’s reflection library. So let’s at present focus on how we are able to obtain this utilizing reflection.
Let’s consisted following class comprise one personal area and one personal technique.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package deal org.techzoo.beans;
public class Message {
personal String sender, reveiver, message;
personal int size;
personal static last int MAX_LENGTH = 120;
public Message(String sender, String reveiver,
String message) {
this.sender = sender;
this.reveiver = reveiver;
this.message = message;
if(this.message != null) {
computeMsgLength();
}
}
personal void computeMsgLength(){
int msgLength = this.message.size();
if(msgLength < 120) this.size = msgLength;
else this.size = MAX_LENGTH;
}
personal String getSenderNoWithISDCode() {
//take into account sender belongs to INDIA
// and has quantity like +91-92729XXXXX
String isdCode = this.sender.substring(0, 3);
return isdCode;
}
public int getLength(){
return this.size;
}
}
|
The above class has a way computeMsgLength() which is personal to the category. Now if we wish to entry this technique out website of the category/package deal then we have to use java reflection api.
To make any area/technique accessible from exterior its scope, use setAccessiable() technique of Subject/Technique class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
package deal org.techzoo.reflections;
import java.lang.replicate.Subject;
import java.lang.replicate.Technique;
import org.techzoo.beans.Message;
public class PrivateMethodTest {
public static void major(String[] args) throws Exception {
Message msg = new Message(“+91-92709XXXXX”, “+91-995566XXXX”,
“Junaid, come quick. We’re ready for U.”);
Class<Message> klass = (Class<Message>) msg.getClass();
Subject size = klass.getDeclaredField(“size”);
size.setAccessible(true);
int leng = (Integer)size.get(msg);
System.out.println(“Message Size : “ + leng);
// calling personal technique…
Technique isdCodeMethod = klass.getDeclaredMethod(
“getSenderNoWithISDCode”, null);
isdCodeMethod.setAccessible(true);
String isdCode = (String)isdCodeMethod.invoke(msg, null);
System.out.println(“ISD Code: “+isdCode);
}
}
|
Supply techzoo.org