This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Java Reflection: Getting fields and methods in declaration order
Java. Get declared methods in order they apear in source code
Suppose I have this class
Is possible take the getters methods in order?
public class ClassA {
private String name;
private Integer number;
private Boolean bool;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Boolean getBool() {
return bool;
}
public void setBool(Boolean bool) {
this.bool = bool;
}
}
I have try this..
for (Method method : ClassA.class.getDeclaredMethods()) {
if (!(method.getReturnType().toString().equals("void"))) {
method.invoke(obj, new Object[0])));
}
}
I got this from documentation
...The elements in array returned are not sorted and are not in any particular order...
So.. is just that? Exists some alternative or I just have to implement something?
You can add to each method your own #annotation, which contains a number. Then get all the getter methods, and use your custom sorter to sort them depending on the number you passed to the annotation using Collections.sort().
Eg:
#SortedMethod(100)
public String getName()
{
return name;
}
#SortedMethod(200)
public String getNumber()
{
return number;
}
Related
I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?
I can get the int values of the statuses but would like the option of getting the string values from the ints as well.
public enum Status {
PAUSE(0),
START(1),
STOP(2);
private final int value;
private Status(int value) {
this.value = value
}
public int getValue() {
return value;
}
}
if status is of type Status enum, status.name() will give you its defined name.
You can use values() method:
For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.
Use default method name() as given bellows
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
You can add this method to your Status enum:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
You can use custom values() method:
public enum SortType
{
Scored, Lasted;
public int value(){
return this == Lasted ? 1:0;
}
}
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed last year.
I have two class in class Flight there is get and set value method and another class i have created a arraylist in which i want to create a database of all flights which contains name,location and time of flight and want to set that value in class Flight method setname. When i run this below code i got an error that "cannot find symbol" in class Model line: flights.add(new Flight.setname("xyz"));
class 2:
First cl
public class Flight {
private String name;
private String location;
private int time;
public String getname()
{
return name;
}
public void setname(String name)
{
this.name= name;
}
public String getlocation()
{
return location;
}
public void setlocation(String location)
{
this.location= location;
}
public int getime()
{
return time;
}
public void settime(int time)
{
this.time = time;
}
}
}
Second class
import java.util.*;
public class Model {
private ArrayList<Flight> flight = new ArrayList<Flight>();
public void flights()
{
flight.add(new Flight.setname("xyz"));
}
}
the problems with your code:
the call to constructor is missing parenthesis new Flight()
the setter method setname("xyz") is defined as returning void. so you are trying to add "void" to the array list.
there is actually a design pattern that allows to construct new instance of Flight, populate its properties (instance variables) and add the instance to the array list: The builder pattern
here is a demonstration of the pattern with one property
public class Flight {
private String name;
private String location;
private int time;
public Flight withName(String name) {
setName(name);
return this;
}
public void setName(String name) {
this.name= name;
}
public static Flight newFlight() {
return new Flight();
}
}
flight.add(newFlight().withName("xyz")...);
This question already has answers here:
What does "this" mean? [duplicate]
(6 answers)
Closed 8 years ago.
in the class Student here what does the keyword this used in the functions refer to?
what does it return exactly?
is it only used in java or c/c++ also?
is there any difference if used in any other language?
class Student
{
private String name;
private String section;
public static Comparator BY_NAME = new ByName();
public static Comparator BY_SECTION = new BySection();
public void setName(String name) {
this.name = name;
}
public void setSection(String section) {
this.section = section;
}
public String getName()
{
return this.name;
}
public String getSection()
{
return this.section;
}
private static class ByName implements Comparator
{
public int compare(Object s1, Object s2)
{
return ((Student)s1).name.compareTo(((Student)s2).name);
}
}
private static class BySection implements Comparator
{
public int compare(Object s1, Object s2)
{
return ((Student)s1).section.compareTo(((Student)s2).section);
}
}
}
In Java and c++ "this" is referring to the object's variable and NOT the class's variable.
I have following two classes:
public Class A{
String name;
Integer age;
//setters and getters
}
And
public Class B{
String name;
Integer age;
Integer height;
//setters and getters
}
and following method
public String getMyName(B b){
return b.getName()+" "+b.getAge()+" "+b.getHeight();
}
Is it possible to refactor this method to use generics which will allow me to call it for objects of those two different classes?
E.g
public <T> String getMyName(T t){
return t.getName()+" "+t.getAge()+( t instanceof B ? " "+t.getHeight() : "");
}
Of course it doesn't work since t doesn't know methods getName, getAge and getHeight.
Classes are not in any relation( I know that they can inherit from one common class and use <T extends C> but they don't have superclass or common interface)
No, without using a common interface or superclass this is not possible with generics. You could use reflection but I'd advice against that and suggest providing a common interface instead.
As others said, there would be other ways to handle that case (e.g. method overloading or passing Object and using instanceof and casts) but if you can use a common interface, I'd still go that way.
Note that Java generics are unlinke C++ generics/templates which would allow what you want to do - and there are good reasons for that difference.
This is the place where people shout the line Programming with interfaces.
Take a an interface and add common methods to it and create a generic method which takes that interface as a argument.
That makes your life easy.
You can use instanceof to check whether is compatible type and if it is, cast object to your type and call methods. It is not elegant way, but still. So this way, you can use your method as generic. :)
You can dynamically adapt them on the fly - something like:
public class A {
String name;
Integer age;
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
}
public class B {
String name;
Integer age;
Integer height;
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public Integer getHeight() {
return height;
}
}
// Create a common interface.
public interface AorB {
public String getName();
public Integer getAge();
// Use Java 8 to implant a default getHeight if it is missing.
default Integer getHeight() {
return 0;
}
}
// Dynamicaly adapt each type.
public String getMyName(A a) {
// Adapt it on the fly.
return getMyName(new AorB() {
#Override
public String getName() {
return a.getName();
}
#Override
public Integer getAge() {
return a.getAge();
}
});
}
public String getMyName(B b) {
// Adapt it on the fly.
return getMyName(new AorB() {
#Override
public String getName() {
return b.getName();
}
#Override
public Integer getAge() {
return b.getAge();
}
#Override
public Integer getHeight() {
return b.getHeight();
}
});
}
// Your method almost untouched.
public String getMyName(AorB ab) {
return ab.getName() + " " + ab.getAge() + " " + ab.getHeight();
}
public void test() {
A a = new A();
a.name = "A";
a.age = 10;
B b = new B();
b.name = "B";
b.age = 10;
b.height = 12;
System.out.println("A:" + getMyName(a));
System.out.println("B:" + getMyName(b));
}
I am using Java-8 default here to implement a default getHeight but it would not take much effort to eliminate that - you would need to implement a getHeight for the getMyName(A) method.
Sadly - of course - this is not using generics in the solution so you may see this as not an answer to your question but it is an alternate solution to your problem so I chose to post.
I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?
I can get the int values of the statuses but would like the option of getting the string values from the ints as well.
public enum Status {
PAUSE(0),
START(1),
STOP(2);
private final int value;
private Status(int value) {
this.value = value
}
public int getValue() {
return value;
}
}
if status is of type Status enum, status.name() will give you its defined name.
You can use values() method:
For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.
Use default method name() as given bellows
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
You can add this method to your Status enum:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
I believe enum have a .name() in its API, pretty simple to use like this example:
private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }
private enum Security {
low,
high
}
With this you can simply call
yourObject.security()
and it returns high/low as String, in this example
You can use custom values() method:
public enum SortType
{
Scored, Lasted;
public int value(){
return this == Lasted ? 1:0;
}
}