reflection example

Hi,

I am trying below example

http://examples.javacodegeeks.com/core-java/reflection/java-reflection-example/

package com.javacodegeeks.core.reflection;

import java.lang.reflect.*;
import java.util.Arrays;

public class ReflectionExample {
	public static void main(String[] args) {

		// Obtain the class object if we know the name of the class
		Class rental = RentCar.class;
		try {
			// get the absolute name of the class
			String rentalClassPackage = rental.getName();
			System.out.println("Class Name is: " + rentalClassPackage);

			// get the simple name of the class (without package info)
			String rentalClassNoPackage = rental.getSimpleName();
			System.out.println("Class Name without package is: "
					+ rentalClassNoPackage);

			// get the package name of the class
			Package rentalPackage = rental.getPackage();
			System.out.println("Package Name is: " + rentalPackage);

			// get all the constructors of the class
			Constructor[] constructors = rental.getConstructors();
			System.out.println("Constructors are: "
					+ Arrays.toString(constructors));

			// get constructor with specific argument
			Constructor constructor = rental.getConstructor(Integer.TYPE);

			// initializing an object of the RentCar class
			RentCar rent = (RentCar) constructor.newInstance(455);

			// get all methods of the class including declared methods of
			// superclasses
			// in that case, superclass of RentCar is the class java.lang.Object
			Method[] allmethods = rental.getMethods();
			System.out.println("Methods are: " + Arrays.toString(allmethods));
			for (Method method : allmethods) {
				System.out.println("method = " + method.getName());
			}

			// get all methods declared in the class
			// but excludes inherited methods.
			Method[] declaredMethods = rental.getDeclaredMethods();
			System.out.println("Declared Methods are: "
					+ Arrays.toString(declaredMethods));
			for (Method dmethod : declaredMethods) {
				System.out.println("method = " + dmethod.getName());
			}

			// get method with specific name and parameters
			Method oneMethod = rental.getMethod("computeRentalCost",
					new Class[] { Integer.TYPE });
			System.out.println("Method is: " + oneMethod);

			// call computeRentalCost method with parameter int
			oneMethod.invoke(rent, 4);

			// get all the parameters of computeRentalCost
			Class[] parameterTypes = oneMethod.getParameterTypes();
			System.out.println("Parameter types of computeRentalCost() are: "
					+ Arrays.toString(parameterTypes));

			// get the return type of computeRentalCost
			Class returnType = oneMethod.getReturnType();
			System.out.println("Return type is: " + returnType);

			// gets all the public member fields of the class RentCar
			Field[] fields = rental.getFields();

			System.out.println("Public Fields are: ");
			for (Field oneField : fields) {
				// get public field name
				Field field = rental.getField(oneField.getName());
				String fieldname = field.getName();
				System.out.println("Fieldname is: " + fieldname);

				// get public field type
				Object fieldType = field.getType();
				System.out.println("Type of field " + fieldname + " is: "
						+ fieldType);

				// get public field value
				Object value = field.get(rent);
				System.out.println("Value of field " + fieldname + " is: "
						+ value);

			}

			// How to access private member fields of the class

			// getDeclaredField() returns the private field
			Field privateField = RentCar.class.getDeclaredField("type");

			String name = privateField.getName();
			System.out.println("One private Fieldname is: " + name);
			// makes this private field instance accessible
			// for reflection use only, not normal code
			privateField.setAccessible(true);

			// get the value of this private field
			String fieldValue = (String) privateField.get(rent);
			System.out.println("fieldValue = " + fieldValue);

		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}

Open in new window

package com.javacodegeeks.core.reflection;

public class RentCar {

	private int rate;
	private String type;
	public int price;

	public RentCar(int length) {
		if (length < 455) {
			type = "small";
			rate = 35;
		} else if ((length >= 455) && (length < 495)) {
			type = "mid-sized";
			rate = 45;
		} else if (length >= 495) {
			type = "large";
			rate = 55;
		}
	}


	public int getRate() {
		return rate;
	}

	public String getType() {
		return type;
	}

	public void setRate(int rate) {
		this.rate = rate;
	}

	public void setType(String type) {
		this.type = type;
	}

	public void computeRentalCost(int numDays) {
		price = numDays * rate;
		System.out
				.println("The cost of your rental car is " + price + " euros");
	}
}

Open in new window


i got below output
Class Name is: com.javacodegeeks.core.reflection.RentCar
Class Name without package is: RentCar
Package Name is: package com.javacodegeeks.core.reflection
Constructors are: [public com.javacodegeeks.core.reflection.RentCar(int)]
Methods are: [public boolean java.lang.Object.equals(java.lang.Object), public native int java.lang.Object.hashCode(), public java.lang.String java.lang.Object.toString(), public int com.javacodegeeks.core.reflection.RentCar.getRate(), public java.lang.String com.javacodegeeks.core.reflection.RentCar.getType(), public void com.javacodegeeks.core.reflection.RentCar.setRate(int), public void com.javacodegeeks.core.reflection.RentCar.setType(java.lang.String), public void com.javacodegeeks.core.reflection.RentCar.computeRentalCost(int), public final native java.lang.Class java.lang.Object.getClass(), public final native void java.lang.Object.notify(), public final native void java.lang.Object.notifyAll(), public final void java.lang.Object.wait() throws java.lang.InterruptedException, public final void java.lang.Object.wait(long) throws java.lang.InterruptedException, public final native void java.lang.Object.wait(long,int) throws java.lang.InterruptedException]
method = equals
method = hashCode
method = toString
method = getRate
method = getType
method = setRate
method = setType
method = computeRentalCost
method = getClass
method = notify
method = notifyAll
method = wait
method = wait
method = wait
Declared Methods are: [public int com.javacodegeeks.core.reflection.RentCar.getRate(), public java.lang.String com.javacodegeeks.core.reflection.RentCar.getType(), public void com.javacodegeeks.core.reflection.RentCar.setRate(int), public void com.javacodegeeks.core.reflection.RentCar.setType(java.lang.String), public void com.javacodegeeks.core.reflection.RentCar.computeRentalCost(int)]
method = getRate
method = getType
method = setRate
method = setType
method = computeRentalCost
Method is: public void com.javacodegeeks.core.reflection.RentCar.computeRentalCost(int)
The cost of your rental car is 180 euros
Parameter types of computeRentalCost() are: [int]
Return type is: void
Public Fields are:
Fieldname is: price
Type of field price is: int
Value of field price is: 180
One private Fieldname is: type
fieldValue = mid-sized

i was not clear on how i got below output

One private Fieldname is: type

                 // How to access private member fields of the class

                  // getDeclaredField() returns the private field
                  Field privateField = RentCar.class.getDeclaredField("type");

                  String name = privateField.getName();
                  System.out.println("One private Fieldname is: " + name);
                  // makes this private field instance accessible
                  // for reflection use only, not normal code
                  privateField.setAccessible(true);

                  // get the value of this private field
                  String fieldValue = (String) privateField.get(rent);
                  System.out.println("fieldValue = " + fieldValue);

what is 'rent' here. How 'type' was printed as filedValue. please advise
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gudii9Author Commented:
what is 455 in code?
0
gurpsbassiCommented:
455 is the argument supplied to the RentCar constructor method
0
mccarlIT Business Systems Analyst / Software DeveloperCommented:
i was not clear on how i got below output

One private Fieldname is: type

What is not clear, on line 96, the code is asking to get the field named "type" and so when on line 98,99, the code gets the name of the field and prints it, you get "type"


what is 'rent' here.

'rent' is the object of which to get the value of the privateField. For example, say you have a "Dog" class that has a field called "colour" that can hold the colour of each Dog object that gets created. You can then get a "Field" object from the Dog class that represents the colour field, lets call this field object... colourField. Now you create two instances of Dog class, one id dog1 and has the colour brown, another is dog2 and has the colour white. Now you can do this....   colourField.get(dog1)   and it will return brown, and you can do....    colourField.get(dog2)    and it will return white.



How 'type' was printed as filedValue. please advise

I can't see anywhere where 'type' was printed as a fieldValue.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java EE

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.