Get a field's value - java

I want to get the value with which the field is being initialized.
Example:
class ClassA {
public String someString = "Merry Christmas";
}
class ClassB {
String anotherString = ClassA.class.getField("someString");
}
Is there any way to do this?

This would be possible if ClassA.string were static. In this case you would be able to get the value through reflection without the need to get a hold of an instance of ClassA inside of which someString is defined:
class ClassA {
public static String someString = "Merry Christmas";
}
...
Object s = ClassA.class.getField("someString").get(null);
Demo 1.
If the variable is not static, and you simply want to get its initial value, you could still do it, assuming that ClassA has a default constructor:
public static void demo(Class<?> cl) throws Exception {
Object s = cl.getField("someString").get(cl.newInstance());
System.out.println(s);
}
Demo 2.

You first have to create an instance o ClassA into ClassB:
ClassA a = new ClassA();
System.out.println(a.someString);
But according to the current format of your code, the best option would be declaring someString static: public static String someString = "Merry Christmas";. Then you can directly access this field from any other class of any package (as it's public):
System.out.println(ClassA.someString);

I think you do not fully understand what a (non-static) field means: it means the field has a specific value for each instance (object) of ClassA, so you cannot access the fields content, because there can be thousands, each with a different value.
There are several options:
A possible solution is to make the field static:
ClassA {
public static String someString = "Merry Christmas";
}
ClassB {
String anotherString = ClassA.someString;
}
Or as #toubou says, you can construct an object and access the field of that specific object. Note however that fields represent an object's state, and therefore can modify.

Related

What does this refers to in these methods? [duplicate]

Normally, I use this in constructors only.
I understand that it is used to identify the parameter variable (by using this.something), if it have a same name with a global variable.
However, I don't know that what the real meaning of this is in Java and what will happen if I use this without dot (.).
this refers to the current object.
Each non-static method runs in the context of an object. So if you have a class like this:
public class MyThisTest {
private int a;
public MyThisTest() {
this(42); // calls the other constructor
}
public MyThisTest(int a) {
this.a = a; // assigns the value of the parameter a to the field of the same name
}
public void frobnicate() {
int a = 1;
System.out.println(a); // refers to the local variable a
System.out.println(this.a); // refers to the field a
System.out.println(this); // refers to this entire object
}
public String toString() {
return "MyThisTest a=" + a; // refers to the field a
}
}
Then calling frobnicate() on new MyThisTest() will print
1
42
MyThisTest a=42
So effectively you use it for multiple things:
clarify that you are talking about a field, when there's also something else with the same name as a field
refer to the current object as a whole
invoke other constructors of the current class in your constructor
The following is a copy & paste from here, but explains very well all different uses of the this keyword:
Definition: Java’s this keyword is used to refer the current instance of the method on which it is used.
Following are the ways to use this:
To specifically denote that the instance variable is used instead of static or local variable. That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the this denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
this is used to refer the constructors
public JavaQuestions(String javapapers) {
this(javapapers, true);
}
This invokes the constructor of the same java class which has two parameters.
this is used to pass the current java instance as parameter
obj.itIsMe(this);
Similar to the above this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
this can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by
Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, this is associated with its instance and this will not work in static methods.
To be complete, this can also be used to refer to the outer object
class Outer {
class Inner {
void foo() {
Outer o = Outer.this;
}
}
}
It refers to the current instance of a particular object, so you could write something like
public Object getMe() {
return this;
}
A common use-case of this is to prevent shadowing. Take the following example:
public class Person {
private final String name;
public Person(String name) {
// how would we initialize the field using parameter?
// we can't do: name = name;
}
}
In the above example, we want to assign the field member using the parameter's value. Since they share the same name, we need a way to distinguish between the field and the parameter. this allows us to access members of this instance, including the field.
public class Person {
private final String name;
public Person(String name) {
this.name = name;
}
}
Quoting an article at programming.guide:
this has two uses in a Java program.
1. As a reference to the current object
The syntax in this case usually looks something like
this.someVariable = someVariable;
This type of use is described here: The 'this' reference (with examples)
2. To call a different constructor
The syntax in this case typically looks something like
MyClass() {
this(DEFAULT_VALUE); // delegate to other constructor
}
MyClass(int value) {
// ...
}
This type of use is described here: this(…) constructor call (with examples)
In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.
public class MyDialog extends JDialog implements ActionListener
{
public MyDialog()
{
JButton myButton = new JButton("Hello");
myButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
System.out.println("Hurdy Gurdy!");
}
}
It's "a reference to the object in the current context" effectively. For example, to print out "this object" you might write:
System.out.println(this);
Note that your usage of "global variable" is somewhat off... if you're using this.variableName then by definition it's not a global variable - it's a variable specific to this particular instance.
It refers to the instance on which the method is called
class A {
public boolean is(Object o) {
return o == this;
}
}
A someA = new A();
A anotherA = new A();
someA.is(someA); // returns true
someA.is(anotherA); // returns false
The this Keyword is used to refer the current variable of a block, for example consider the below code(Just a exampple, so dont expect the standard JAVA Code):
Public class test{
test(int a) {
this.a=a;
}
Void print(){
System.out.println(a);
}
Public static void main(String args[]){
test s=new test(2);
s.print();
}
}
Thats it. the Output will be "2".
If We not used the this keyword, then the output will be : 0
Objects have methods and attributes(variables) which are derived from classes, in order to specify which methods and variables belong to a particular object the this reserved word is used. in the case of instance variables, it is important to understand the difference between implicit and explicit parameters. Take a look at the fillTank call for the audi object.
Car audi= new Car();
audi.fillTank(5); // 5 is the explicit parameter and the car object is the implicit parameter
The value in the parenthesis is the implicit parameter and the object itself is the explicit parameter, methods that don't have explicit parameters, use implicit parameters, the fillTank method has both an explicit and an implicit parameter.
Lets take a closer look at the fillTank method in the Car class
public class Car()
{
private double tank;
public Car()
{
tank = 0;
}
public void fillTank(double gallons)
{
tank = tank + gallons;
}
}
In this class we have an instance variable "tank". There could be many objects that use the tank instance variable, in order to specify that the instance variable "tank" is used for a particular object, in our case the "audi" object we constructed earlier, we use the this reserved keyword. for instance variables the use of 'this' in a method indicates that the instance variable, in our case "tank", is instance variable of the implicit parameter.
The java compiler automatically adds the this reserved word so you don't have to add it, it's a matter of preference. You can not use this without a dot(.) because those are the rules of java ( the syntax).
In summary.
Objects are defined by classes and have methods and variables
The use of this on an instance variable in a method indicates that, the instance variable belongs to the implicit parameter, or that it is an instance variable of the implicit parameter.
The implicit parameter is the object the method is called from in this case "audi".
The java compiler automatically adds the this reserved word, adding it is a matter of preference
this cannot be used without a dot(.) this is syntactically invalid
this can also be used to distinguish between local variables and global variables that have the same name
the this reserve word also applies to methods, to indicate a method belongs to a particular object.
Instance variables are common to every object that you creating. say, there is two instance variables
class ExpThisKeyWord{
int x;
int y;
public void setMyInstanceValues(int a, int b) {
x= a;
y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
}
class Demo{
public static void main(String[] args){
ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();
obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);
}
}
if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method.
How do you think JVM correctly assign the values for every object?
there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;
public void setMyInstanceValues(int a, int b) {
this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
this.y=b;
System.out.println("x is ="+x);
System.out.println("y is ="+y);
}
(I know Im late but shh Im being the sneaky boi you never saw me)
The this keyword in most Object Oriented programming languages if not all means that its a reference towards the current object instance of that class. It's essentially the same thing as calling on that object from outside of the method by name. That probably made no sense so Ill elaborate:
Outside of the class, in order to call something within that instance of the object, for example a say you have an object called object and you want to get a field you would need to use
object.field
Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use
this.field
The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn't much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this:
(Hah, get it? this? Hehe .... just me? okay :( I'll leave now)
public String Name;
//Constructor for {object} class
public object(String Name){
Name = Name;
}
That would cause some problems, the compiler wouldn't be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class' field declarations so it would instead assign the Name parameter to.... the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:
public String Name;
//Constructor for {object} class
public object(String Name){
this.Name = Name;
}
This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.
To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword "this", meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.
this is a reference to the current object: http://download.oracle.com/javase/tutorial/java/javaOO/thiskey.html
this can be used inside some method or constructor.
It returns the reference to the current object.
This refers to the object you’re “in” right now. In other words,this refers to the receiving object. You use this to clarify which variable you’re referring to.Java_whitepaper page :37
class Point extends Object
{
public double x;
public double y;
Point()
{
x = 0.0;
y = 0.0;
}
Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
In the above example code this.x/this.y refers to current class that is Point class x and y variables where
(double x,double y) are double values passed from different class to assign values to current class .
A quick google search brought this result: Link
Pretty much the "this" keyword is a reference to the current object (itself).
I was also looking for the same answer, and somehow couldn't understand the concept clearly. But finally I understood it from this link
this is a keyword in Java. Which can be used inside method or constructor of class. It(this) works as a reference to a current object whose method or constructor is being invoked. this keyword can be used to refer any member of current object from within an instance method or a constructor.
Check the examples in the link for a clear understanding
If the instance variables are same as the variables that are declared in the constructor then we use "this" to assign data.
class Example{
int assign;// instance variable
Example(int assign){ // variable inside constructor
this.assign=assign;
}
}
Hope this helps.
In Java "this" is a predefined variable. If we use "this" in method that's mean we are getting the reference (address) of the currently running object. For an example.
this.age ---> age of the currently running object.
I would like to share what I understood from this keyword.
This keyword has 6 usages in java as follows:-
1. It can be used to refer to the current class variable.
Let us understand with a code.*
Let's understand the problem if we don't use this keyword by the example given below:
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
id_no = id_no;
name=name;
salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:-
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.
class Employee{
int id_no;
String name;
float salary;
Student(int id_no,String name,float salary){
this.id_no = id_no;
this.name=name;
this.salary = salary;
}
void display(){System.out.println(id_no +" "+name+" "+ salary);}
}
class TestThis1{
public static void main(String args[]){
Employee s1=new Employee(111,"ankit",5000f);
Employee s2=new Employee(112,"sumit",6000f);
s1.display();
s2.display();
}}
output:
111 ankit 5000
112 sumit 6000
2. To invoke the current class method.
class A{
void m(){System.out.println("hello Mandy");}
void n(){
System.out.println("hello Natasha");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello Natasha
hello Mandy
3. to invoke the current class constructor. It is used to constructor chaining.
class A{
A(){System.out.println("hello ABCD");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output:
hello ABCD
10
4. to pass as an argument in the method.
class S2{
void m(S2 obj){
System.out.println("The method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output:
The method is invoked
5. to pass as an argument in the constructor call
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:-
10
6. to return current class instance
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output:-
Hello
Also, this keyword cannot be used without .(dot) as it's syntax is invalid.
As everyone said, this represents the current object / current instance. I understand it this way,
if its just "this" - it returns class object, in below ex: Dog
if it has this.something, something is a method in that class or a variable
class Dog {
private String breed;
private String name;
Dog(String breed, String name) {
this.breed = breed;
this.name = name;
}
public Dog getDog() {
// return Dog type
return this;
}
}
The expression this always refers to the current instance.
In case of constructors, the current instance is the freshly allocated object that's currently being constructed.
In case of methods, the current instance is the instance on which you have called the method.
So, if you have a class C with some method m, then
during the construction of a fresh instance x of C, the this inside of the constructor will refer to x.
When x is an instance of C, and you invoke x.m(), then within the body of m, this will refer to the instance x.
Here is a code snippet that demonstrates both cases:
public class Example {
static class C {
public C whatDoesThisInConstructorReferTo;
public C() {
whatDoesThisInConstructorReferTo = this;
}
public C whatDoesThisInMethodReferTo() {
return this;
}
}
public static void main(String args[]) {
C x = new C();
System.out.println(x.whatDoesThisInConstructorReferTo == x); // true
System.out.println(x.whatDoesThisInMethodReferTo() == x); // true
}
}
Regarding other syntactical elements that are unrelated to the this-expression:
The . is just the ordinary member access, it works in exactly the same way as in all other circumstances, nothing special is happening in case of this.
The this(...) (with round parentheses) is a special syntax for constructor invocation, not a reference.

Android Java, How to get the value of class attribute?

I want to get the value a class attribute, But I am getting exception : java.lang.NoSuchFieldException
Person.class
public class Person {
public static final String name = "person name";
}
MainActivity.class
...
private void method() {
Class myClass = Person.class;
String name = myClass.getField("name");
}
...
I am getting a java.lang.NoSuchFieldException exception for the getField method.
I tried these solutions but with no avail ...
Change getField method to getDeclaredField
Surround the code by try/catch, and got another error (Incompatible types : java.lang.String and java.lang.reflect.Field)
Invalidate Android Studio caches and restart
I don't Know how to access this value, Any solutions or suggestions are welcomed.
Thanks in advance.
Change getField method to getDeclaredField
Surround the code by try/catch, and got another error (Incompatible
types : java.lang.String and java.lang.reflect.Field)
that because getDeclaredField will return object of type Field not String,
just change your code to this
Field field = myClass.getDeclaredField("name");
//do something with field
If you want to access the value of the field, you can use the get(...) method with a null argument - since it's a static field, it does not require any instance:
private void method() {
Class myClass = Person.class;
Field field = myClass.getField("name");
String name = field.get(null);
Log.d("Test", "field value: " + name);
}
In your case, it doesn't matter whether you use getField(...) or getDeclaredField(...). You would want to use the latter if you want to grab a field in its superclass or an interface implemented by your class.
For example, if Person were to extend from a class that has a field named sample, you would need to use getDeclaredField("sample") instead.
If your variable in the class "Person" is static:
(This is not the best solution in my opinion)Explanation: getField method returns a type "field" so you CAN NOT save into a variable from another type without a conversion.
YourField.get returns an object so you CAN NOT save into a variable from another type without a conversion.
try{
Class _person = Person.class;
Field field = _person.getField("name");
Object value = field.get(null);
String valueString = (String)value; /*The String you are looking for*/
}catch (Exception e) {
//TODO handle exception
}
If your variable in the class "Person" is static:
String valueString = Person.name /*The value you are looking for*/
If your variable isn't static but public:
IMPORTANT (If you have not set a default value to the variable): In this case the value will be an empty string because you are creating a new instance of your calss. You can set the "person name" in the constructor of your Person class another way you will get an empty string because the variable isn't static.
Person _person = new Person();
String personName = _person.name;
Since that's a constant you declared, access it directly with the class name as below,
String name = Person.name;
It's a static constant. Static means there is only one value at a time possible. Or say it like this: The class attribute 'name' is a class attribute, not an object attribute! The attribute belongs to the class!
So you don't need to create an instance of your Person class.
You just can use:
String name = Person.name;
Remember: this only works cause the name belongs to the class. And it does so, because you declared your name variable static.

class variables

This might be a dumb question but I had this question hover around me. Is there any difference between class variables and member variables in java or they both one and the same.
class Example {
protected String str;
public static String str1 = "xyz";
}
I know that str1 is a class variable, is str also a class variable?
Yes, the difference is, there is only one per class when we talk about class attributes and there is one per object when we talk about instance attribute.
In your code protected String str declares an instance attribute ( or member variable as you call it ) and public static String str1 = "xyz" declares a class attribute.
There is a big difference.
Member variables are tied to an instance object of the class. So the variable's value can be different for different instance objects.
The static variable is one for the whole class - you don't need to instantiate an object to access it.
class A {
public int memberVar;
public static int staticVar;
}
void Test() {
A obj = new A();
int var = obj.memberVar;
//var = A.memberVar -- wrong!
//vs
var = A.staticVar;
}
They are not the same, and str isn't a class variable - the "static" indicates a class variable.
The fundamental difference is that class (static) variables can be thought of as shared between all instance of the class, whereas there is an independent copy of each member (instance) variable for each instance of the class.
str is not a class variable. str is an instance variable.
Class variable
a class variable is a variable defined
in a class (i.e. a member variable) of
which a single copy exists, regardless
of how many instances of the class
exist
Instance variable
a variable defined in a class (i.e. a
member variable), for which each
object of the class has a separate
copy
By these definitions, str1 is a class variable, and str is not.
There is a difference. str1 is a class variable that has 1 value for all instances of the class. The str variable is an instance variable, and each instance of Example (aka, new Example()) can have a different value of str, but all instances of Example will share the same value of str1.
If you try to implement a counter inside your class that counts how many instances have been created, you will see immediately why class variables can do the work, while instance variables can not.
public class MyClass {
private static int count;
public MyClass() {
count++;
...
}
public static int getCount() {
return count;
}
...
}
You can call MyClass.getCount(); even before having created a single MyClass instance.
str1 is a class variable as static is the modifier to it. static means variable belongs to a class not to the instance.
str variable does not have static modifier which makes it member or instance variable.
each instance of a class will have its own copy of member variable

Accesing a method from another class file?

I need to acces a variable (an int) from another class file. How would I do this? It's a public int, I need to get the int value and put it into a file.
If you have an instance:
AnotherClass another = new AnotherClass();
Then if the field (instance variable) is public:
another.someField;
or if you have a getter method
another.getSomeField();
If none of these is true - add a getter method (this is the preferred way to access instance variables).
If you can't change the class - as a last resort you can use reflection.
Example:
MyClass myclass = new MyClass();
System.out.print(myclass.myint)
Best practice code states that if the variable is not a Static Final, then you should create getters & setters inside the class:
public class Main{
int variableName;
public int getVariableName(){
return this.variableName;
}
public setVariableName(int variableName){
this.variableName = variableName;
}
}
If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method:
Main m = new Main();
int a = m.getVariableName();
Hope it helps.
If you have an instance of that other class, you access it as {instance}.varable.
That varaiable need to either be public, or it needs to be in the same package and not private, or it must be a protected variable in a superclass.
If the variable is static, then you don't need an instance of that class, you would access it like {ClassName}.variable.
Far and away the best thing to do here would be to make the int you need to access a Property of the other class and then access it with a 'getter' method.
Basically, in the other class, do this:
public int Number
{
get
{
return number;
}
set
{
number = value;
}
}
private int number;
Doing this allows you to easily set that in to something else if you need to or to get it's current value. To do this, create an instance of the "AnotherClass" as Bozho already explained.

How do I create a constant object in Java?

How do I create a reference to a constant object?
final Myclass obj = new Myclass();
does not work, it says obj(the reference) should not be re-assigned but we can still change the object referred. I want to ensure that the object itself does not change once constructed.
Just make it immutable (like String is). Or wrap it in another object which restricts access to mutators of the object in question (like Collections.unmodifiableList() and consorts do).
You are mixing two things: final and immutable.
A variable can be final, so you can't change it's a value (or object reference) after it is initialized (but of course you can change the reference's objects attributes)
An object can be immutable (not a keyword but a property), so you can't change it's value after it is created. The string is a good example - you can not change the backing char[] inside a String object.
What you want is an Immutable Object. There are no keywords in Java that can instantly make an object immutable. You have to design the object's logic, so that its state cannot be changed. As BalusC put, you can wrap it in another object which restricts access to its mutators.
I don't think there's any built in keyword to make that possible in Java. Even if the reference is constant/final, the internals of the object could still be changed.
Your best options is to have a ReadOnly implementation version of your class.
You can read more about this here: http://en.wikipedia.org/wiki/Const-correctness#final_in_Java
In Java, an immutable class is generally means that it doesn't have "setters" and any field that can be accessed with a "getter" should also be immutable. In order to get your data into the class to start, you'll need to have a constructor that takes the values as arguments:
public class MyClass {
String something;
int somethingElse;
// The class can only be modified by the constructor
public MyClass(String something, int somethingElse) {
this.something = something;
this.somethingElse = somethingElse;
}
// Access "something". Note that it is a String, which is immutable.
public String getSomething() {
return something;
}
// Access "somethingElse". Note that it is an int, which is immutable.
public int getSomethingElse() {
return somethingElse;
}
}
Yes it does you seem to have forgotten to set the type.
final MyClass obj = new Myclass();
That means that obj can only be assigned once. Java does not have a const keyword like C++ does. If MyClass is not declared final (final class MyClass { ... }) it can still change.
final variables should be assigned in the moment of declaration.
final MyClass obj = new MyClass();
In java object constant means you cannot change its reference but you can change the values of its state variables untill they are not final. if all the member variables are final then its a perfect constant, where you cannot change anything.
Here is a way to wrap any object to make it "roughly" immutable.
All method calls that are not 'getters' will throw an Exception. This code defines a getter as a method that meets these criteria:
name of the method starts with get or is
it takes no arguments
it returns a value (not void return type)
Yes, getter methods could mutate an object. But if your code (or code you are using) is doing that, you have some bigger problems, please go get some help :)
the code:
class ImmutableWrapper
public static <T> T wrap(T thing) {
return (T) Proxy.newProxyInstance(thing.getClass().getClassLoader(), new Class[]{thing.getClass()}, OnlyGettersInvocationHandler.instance);
}
private static class OnlyGettersInvocationHandler implements InvocationHandler {
public static InvocationHandler instance;
#Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final String name = method.getName();
if ((args == null || args.length == 0)
&& (name.startsWith("get") || name.startsWith("is")
&& !method.getReturnType().equals(Void.class))) {
return method.invoke(proxy, args);
} else {
throw new UnsupportedOperationException("immutable object: " + proxy + ", cannot call " + name);
}
}
}
}
SomeClass myThing = ... create and populate some object ...
SomeClass myImmutableThing = ImmutableWrapper.wrap(myThing);
myImmutableThing.setValue('foo'); // throws Exception
myImmutableThing.whatever(); // throws Exception
myImmutableThing.getSomething(); // returns something
myImmutableThing.isHappy(); // returns something
Mayby you can create class with final attributes. So, you can't change it: object == const.
At least "String" immutable because of it:
public final class String implements Serializable, Comparable<String>, CharSequence {
private final char[] value;
//...
}

Categories

Resources