For example, if I have a class Student and an student object inside of it with the value of 5, also some getters and setters
public class Student {
int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void run() {
Student stud = new Student();
stud.setAge(5);
}
}
And I have another class called getStudent
public class GetStudent {
int studAge = stud.getAge;
}
Now this, obviously, gives me an error. Is there any way to access the stud object and it's methods outside of it's class?
If you always want to access the Student object only through the public static void run() method, check out Singleton design pattern.
Related
I can't get this Java code to work. I have read multiple examples, but none explains why the code doesn't work.
The code:
class Main {
public static void main(String[] args) {
class UserInfo {
public String Name = "Example Name";
public int Age = 13;
static int GetAge() {
return (Age);
}
}
UserInfo.GetAge();
}
}
Please note I am very new to Java.
You cannot call non-static method from static context without creating new UserInfo object. You need to create new UserInfo object
class Main {
public static void main(String[] args) {
class UserInfo {
public String Name = "Example Name";
public int Age = 13;
int GetAge() {
return (Age);
}
}
UserInfo userInfo = new UserInfo();
userInfo.GetAge();
}
}
You cannot call a non-static method from a static context. I have moved the class outside of the method and made it static.
Try the code below:
class Main {
public static void main(String[] args) {
System.out.println(UserInfo.GetAge());
}
static class UserInfo {
public String Name = "Example Name";
static int Age = 13;
static int GetAge() {
return (Age);
}
}
}
However, if you want a dynamic class in where you can define the name and age, use this code below:
class Main {
public static void main(String[] args) {
UserInfo userInfo = new UserInfo("John", 13);
System.out.println(String.format("Name: %s Age: %s", userInfo.getName(), userInfo.getAge()));
}
static class UserInfo {
String name;
int age;
UserInfo(String name, int age){
this.name = name;
this.age = age;
}
int getAge() {
return age;
}
String getName() {
return name;
}
}
}
Error 1:
age is an instance variable. You can not use it inside the static method GetAge(), so either make Age static or make a getAge instance...
static int GetAge() {
return (Age);
}
Error 2: you can not access an instance variable GetAge() using a class name reference. To correct it, you have to create an object and use this reference to access it.
UserInfo.GetAge(); // Does not compile
Instead use:
UserInfo userInfo = new UserInfo();
userInfo.GetAge();
Generally, instance variables can not be used inside static methods and you can not use class reference to access an instance member in Java.
First of all, you cannot call a non-static method from a static context. You should need to move the inner class outside from the main method and make it static.
Try this one:
public class Main {
public static void main(String[] args) {
System.out.println(UserInfo.GetAge());
}
static class UserInfo {
public String Name = "Example Name";
public static int Age = 13;
static int GetAge() {
return (Age);
}
}
}
We have developed a Change Watcher .using the CGLIB API. based on the below example
Class Teacher
import java.util.List;
public class Teacher {
private String userName;
private String cource;
private List<Student> students;
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCource() {
return cource;
}
public void setCource(String cource) {
this.cource = cource;
}
}
Student.class
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
ClassFacadeCglib.class
public class ClassFacadeCglib implements MethodInterceptor{
private Object target;
public Object getInstance(Object target) {
this.target = target;
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.target.getClass());
// callback method
enhancer.setCallback(this);
// create proxy object
return enhancer.create();
}
#Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
if(method.getName().startsWith("set")){
System.out.println(method.getName()+" start");
proxy.invokeSuper(obj, args);
System.out.println(method.getName()+" end..");
}
if(method.getName().startsWith("get")){
System.out.println(method.getName()+" start");
proxy.invokeSuper(obj, args);
System.out.println(method.getName()+" end");
}
return null;
}
}
Main.class
public class Main {
public static void main(String[] args) {
ClassFacadeCglib cglib=new ClassFacadeCglib();
Teacher teacher=(Teacher)cglib.getInstance(new Teacher());
teacher.setCource("Math");
teacher.getUserName();
}
}
if these classes belong to the same package and bundle the enhancer.create() returns the proxy object to which we can perform the interceptor process on the Setters of the class.
However if seperate the bundle and packages of the interceptor class the enhacer.create() returns null and this blocks us from going with the interceptor process is there a different approach that we need to follow .
The idea behind separation of bundle and package is to keep the developer code different from the framework code and restrict the outside world to know about the byte code usage..
To summerize the fact.
Class A and Class B (Teacher and Students Classes) candidates for interceptor present in the Package X (developer package)
Class D is the interceptor class(the CGlib class mentioned above) and Class C is the Framework Class both are present in the framework package.
Package Developer
Class Delegate
{
C c =new C()
Teacher teach =(Teacher) c.write(new Teacher());
}
Package Framework
Class C
{
Public Object write(Object model)
{
ClassFacadeCglib cglib=new ClassFacadeCglib();
Object obj=(Object )cglib.getInstance(model); //calls returns
enhancher.create() as null and thus we cannot perform the interceptor steps
return obj;
}
}
I have a constructor with variable initial_Age
public Person(int initial_Age) {
if(initial_Age<0){
age=0;
}
I want to use initial_Age in other methods but it is giving error(variable not initialized)
public void amIOld() {
if(this.initial_Age>0){
age=this.initial_Age;
}
What should I do ?
Try to do something like this:
private int initial_Age;
public Person(int initial_Age) {
this.initial_Age =initial_Age;
if(initial_Age<0){
age=0;
}
And you can use initial_Age everywhere in the Person class.
To answer your question.
public class Person {
private int age;
public Person(int initialAge) {
this.age = Math.max(initialAge, 0);
}
public boolean amIOld() {
return this.age > 0;
}
}
This way the age for one person is constant. U will need to change the logic.
This question already has answers here:
Java Reflection: How can I get the all getter methods of a java class and invoke them
(7 answers)
Closed 8 years ago.
I want to know if I can get the methods that returns class members.
For example I have a class called Person inside this class there is two members that are name and age and inside this class I have 4 methods as follow :
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
so if I use the method Person.class.getDeclaredMethods(); it returns all the methods that are declared inside this class and also Person.class.getDeclaredMethods()[0].getReturnType(); returns the return type of the method.
But what I need is to get the methods that returns the two variables name and age In this case the methods are public String getName() and public int getAge().
What can I do?
In your class name and age are not global. They would need to have a static before them to be global. In order to access your fields with an instance and reflection you could do something like
public static void main(String args[]) {
Person p = new Person("Elliott", 37);
Field[] fields = p.getClass().getDeclaredFields();
for (Field f : fields) {
try {
f.setAccessible(true);
String name = f.getName();
String val = f.get(p).toString();
System.out.printf("%s = %s%n", name, val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output is (as I would expect)
name = Elliott
age = 37
When I run the code below, why does it throw this error?
Exception in thread "main" java.lang.CloneNotSupportedException: Student
at java.lang.Object.clone(Native Method)
at Student.clone(Student.java:44)
at StudentApp.main(StudentApp.java:10)
Here's my main class:
public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("湖南省长沙市林科大","1234567",20);
Student stu = new Student("诸葛亮量",20);
stu.setAddress(address);
Student stu2 = (Student)stu.clone();
stu2.setAddress(new Address("湖南省常德市区","484848348",22));
stu2.setName("张飞飞");
stu2.setAge(23);
stu.sayHi();
stu2.sayHi();
}
This is Student class:
public class Student{
private String name;
private int age;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student() {
super();
}
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public void sayHi() {
System.out.println("大家好,我是" + this.getName() + "同学,我今年" + this.getAge()
+ "岁了……我的HashCode是:" + this.hashCode()+"。我家庭住址是"+address.getAddress()+",家庭住址的HashCode为:"+address.hashCode());
}
}
This is Address Class:
public class Address {
private String address;
private String tel;
private int roadNum;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public int getRoadNum() {
return roadNum;
}
public void setRoadNum(int roadNum) {
this.roadNum = roadNum;
}
public Address() {
super();
}
public Address(String address, String tel, int roadNum) {
super();
this.address = address;
this.tel = tel;
this.roadNum = roadNum;
}
}
From the javadoc
Invoking Object's clone method on an instance that does not implement
the Cloneable interface results in the exception
CloneNotSupportedException being thrown.
Have you tried to make your Student class implement the Cloneable interface?
Instead of attempting to use clone(), write a copy constructor that takes an instance of a Student and copies it's fields individually. Then you don't need to worry about the semantics of clone. In your example, this means having a copy constructor on Address as well, since a student has an Address field.
Read Effective Java by Joshua Bloch for reasons why clone should be avoided.
public class Student {
final private String name;
final private int age;
final private Address address;
public Address getAddress() {
return address;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Student(Student copyStudent) {
this.name = new String(copyStudent.getName());
this.age = copyStudent.getAge();
this.address = new Address(copyStudent.getAddress());
}
}
From Effective Java
The copy constructor approach and its static factory variant have many
advantages over Cloneable/clone: They do not rely on a risk-prone
extralinguistic object creation mechanism; they do not demand
unenforceable adherence to ill-documented conventions; they do not
conflict with the proper use of final fields; they do not require the
client to catch an unnecessary checked exception; and they provide a
statically typed object to the client. While it is impossible to put a
copy constructor or static factory in an interface, Cloneable fails to
function as an interface because it lacks a public clone method.
Therefore you aren’t giving up interface functionality by using a copy
constructor instead of a clone method. Furthermore, a copy constructor
(or static factory) can take an argument whose type is an appropriate
interface implemented by the class. For example, all general-purpose
collection implementations, by convention, provide a copy constructor
whose argument is of type Collection or Map. Interface-based copy
constructors allow the client to choose the implementation of the
copy, rather than forcing the client to accept the implementation of
the original. For example, suppose you have a LinkedList l, and you
want to copy it as an ArrayList. The clone method does not offer this
functionality, but it’s easy with a copy constructor: new
ArrayList(l). Given all of the problems associated with Cloneable, it
is safe to say that other interfaces should not extend it and that
classes designed for inheritance (Item 15) should not implement it.
Because of its many shortcomings, some expert programmers simply
choose never to override the clone method and never to invoke it
except, perhaps, to copy arrays cheaply. Be aware that if you do not
at least provide a well-behaved protected clone method on a class
designed for inheritance, it will be impossible for subclasses to
implement Cloneable.
Student needs to implement Cloneable.
Student and Address both need 'deep' clone, if you don't want to share Address instance both in source and target Student instances:
class Student implements Cloneable {
#Override
protected Object clone() throws CloneNotSupportedException {
Student result = (Student)super.clone();
result.setAddress((Address)getAddress().clone());
return result;
}
...
}
class Address implements Cloneable{
#Override
protected Object clone() throws CloneNotSupportedException {
return (Address) super.clone();
}
...
}