Counting Getters and Setters [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am working on a project that requires to count the number of getters and setters in a compiled java code. I am new to this and dont know where and how to start.
I have installed eclipse and added the Bytecode plugin to see the bytecode of the java code.
Any thoughts on what i need to do next?

You can use java.lang.reflect.* package to get all the class info such as variable, methods, constructors and inner classes.
Example:
public int noOfGettersOf(Class clazz) {
int noOfGetters = 0;
Method[] methods = clazz.getDeclaredMethods()
for(Method method : methods) {
String methodName = method.getName();
if(methodName.startsWith("get") || methodName.startsWith("is")) {
noOfGetters++;
}
}
return noOfGetters;
}
Follow the same approach for setters, one thing you need to consider is boolean getters they usually starts with is instead of get.

You can use Class.getDeclaredMethods(), with something like this
public static int countGets(Class<?> cls) {
int c = 0;
for (java.lang.reflect.Method m : cls.getMethods()) {
if (m.getName().startsWith("get")) {
c++;
}
}
return c;
}
public static int countSets(Class<?> cls) {
int c = 0;
for (java.lang.reflect.Method m : cls.getMethods()) {
if (m.getName().startsWith("set")) {
c++;
}
}
return c;
}

Refer the Apache byte code manipulation library BCEL.
The Byte Code Engineering Library is intended to give users a convenient way to analyze, create, and manipulate (binary) Java class files (those ending with .class).
After that you can use reflection to get the count like this :
public static int getGetterMethodCount(Class<?> cls) {
int n = 0;
for (Method m : cls.getMethods()) {
// To identify the boolean setter "is" is used
if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
n++;
}
}
return n;
}
public static int getSetterMethodCount(Class<?> cls) {
int n = 0;
for (Method m : cls.getMethods()) {
if (m.getName().startsWith("set")) {
n++;
}
}
return n;
}

Related

Where is the solution stub in this program and how would I call a method in it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is a specific question, don't downvote it just because it doesn't help you.
public class Answer {
public static String answer(int n) {
String nums="";
int limit = 10005;
int x=2;
while(limit>0){
if(isPrime(x)){
limit-=String.valueOf(x).length();
nums = nums + String.valueOf(x);
}
x+=1;
}
String out="";
if(n==0){
out="23571";
}else{
for(int i=1;i<6;i++){
out += String.valueOf(nums.charAt(n+i));
}
//Problem Solved: instead of this loop, it should be out = nums.substring(n,n+5)
}
return out;
}
public static boolean isPrime(int number) {
for(int check = 2; check < number; ++check) {
if(number % check == 0) {
return false;
}
}
return true;
}
}
Nothing is wrong with this code as far as I know, I'm just using it as an example for you to use.
"It must implement the answer() method in the solution stub." was in the directions for me, but I don't know much about the vocabulary of programming, I only understand logic behind programming, so this is the only thing I don't know how to solve. So what I am asking is where do I put the "answer()" at in this program?
It was looking for substring, which I didn't include because I haven't used java in about a year and simply forgot about it.
Here as I can figure out you have problems in understanding the meaning of "stub". It is simply the test method as provided by the answer here. And if you want to test the above code you have to implement the main method in your code to do the same. Something like this
public static void main(String [] args){
//Either use Scanner object or provide the hard coded input as per your requirements
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(answer(n));
}
EDIT AS PER OP REQUIREMENT
Okay so as per your requirement it is asking you for the unit test. There are many ways to do it but my preferred is to make stub concrete class
Implementation an stub concrete class in JUNIT
class Answer {
public String answer(int n){
// Code body
return "result"// in your case out variable
}
}
class solution extends Answer {
#Override
public String answer(int n){
//return "your stubbed result";
}
}

Object contains list of object. Find max depth [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have the following class:
class A {
List<A> as;
}
I need to find max depth. For example, I can have this:
A firstA = new A();
A secondA = new A();
A thirdA = new A();
firstA.addA(secondA);
firstA.addA(thirdA);
secondA.addA(new A());
secondA.addA(new A());
I need to return 3.
I tried to do recursive method,
Using Java 8 streams:
class A {
List<A> as;
public int getDepth() {
return 1 + as.stream().mapToInt(A::getDepth).max().orElse(0);
}
}
If you're not familiar with streams, this can be interpreted as 'add 1 to maximum depth of all children or 0 if there are no children'.
If you can't change A you can still use this by passing A into the method:
public class MyClass {
public static int getDepth(A a) {
return 1 + a.as.stream().mapToInt(MyClass::getDepth).max().orElse(0);
}
}
Recursive depth-computing:
public static int computeDepth(A a)
{
int maxDepth = 0;
for(A innerA : a.getAs())
{
int depth = computeDepth(innerA);
if(depth > maxDepth)
maxDepth = depth;
}
return maxDepth + 1;
}

How to be able to use .class from a getConstructor()? - Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In java, I am working on a API for a software I am working on that will allow people to extend the software on their own. Right now, I am currently working one the event system, which is going just fine. I am trying to use .class to get the needed argument type so the function will run. Is there any code I can use to be able to get a variable from a constructor (A string for example that has the class directory) And then make it so I can use .class on it? I would love to know!
Note: if some of the variables or constructors don't look like they are from java, it's probably because they are part of the API I am working on.
Here is my code:
private void throwEvent() {
PSLPE = new PocketServerListPingEvent(this, Packet.getAddress(), Packet.getPort(), ServerSettings.getPEMOTD());
ArrayList<Class<?>> Listeners = PluginManager.getListeners();
for(int i = 0; i < Listeners.size(); i++) {
Method[] MethodList = Listeners.get(i).getMethods();
for(int j = 0; j < MethodList.length; j++) {
if(MethodList[j].isAnnotationPresent(EventHandler.class)) {
if(MethodList[j].getParameters()[0].getType().equals(PocketServerListPingEvent.class)) {
try {
Class<?> EventClass = Class.forName(Listeners.get(i).getName());
Constructor<?>[] EventCtorList = EventClass.getConstructors();
for(int k = 0; k < EventCtorList.length; k++) {
Constructor<?> ctor = EventClass.getConstructor(Class.forName(EventClass.getConstructors()[k].getParameters()[0].getType().toString().substring(6)));
Object EventObject = ctor.newInstance(EventClass.getConstructors()[k].getParameters()[0].getType());
Method EventMethod = EventObject.getClass().getMethod(MethodList[j].getName(), PocketServerListPingEvent.class);
EventMethod.invoke(EventObject, PSLPE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
You are looking for Class.forName.
It returns the Class object for the class with the given name, or throws an exception if there is no such class. For example:
Class<?> chillyDogsClass = Class.forName("net.codeguys.ChillyDogs");
or
String className = new Scanner(System.in).readLine();
try {
Class<?> unknownClass = Class.forName(className);
System.out.println("Successfully found " + unknownClass.toString());
} catch(ClassNotFoundException e) {
System.out.println(className+" doesn't exist!");
}

What is the correct way to return a substring(n, m) within a method statement in Java?

I am going through previous exam questions and my question is what is the correct way or ways to determine a String length and return it.
If the String is less than 5 characters in length then I can return it the following way:
public static String first5(String s){
if(s.length() < 5)
return s;
}
If the String is greater than 5 characters though, it can be returned in the following way:
public static String first5(String s){
return s.substring(0, 4);
}
What I must note is that when I answered this type of question before in an in class test, my lecturer stressed that I should not really use 'magic numbers'?
I am not sure what he actually meant by that though.
Is there a better way to return this type of method at all?
I am still learning Java so please forgive any errors in my syntax.
Many thanks.
This should be your method first5:
public static String first5(String s){
return s.length() < 5? s : s.substring(0, 5);
}
There are no magic numbers here, but maybe the teacher meant the number 5 was a magic number and wanted you to generalize the function:
public static String firstN(String s, int n){
return s.length() < n? s : s.substring(0, n);
}
Note that there's no great shame in using an if statement:
String r = null;
if (s.length() < 5) {
r = s;
}
else {
r = s.substring(0,5);
}
return r;
The logic is clearer than if you use ?:. The advantage of the latter is that it occupies less screen real-estate, so you can get more of a large function onto a screen -- valuable if you have a large function, but counter-productive if not.
Essentially if the requirements ever change, you can easily change the value in one location; thus, it will be changed everywhere it's referenced. You won't have to worry about any fragments of the old requirements floating around in the code. This is generally a good rule to follow with a large chunk of code.
public class solution {
static final int VAR1 = 0;
static final int VAR2 = 4;
static final int VAR3 = 5;
public static String first5(String s){
if(s.length() < VAR3) {
return s;
} else {
return s.substring(VAR1, VAR2);
}
}
}
Of course the variable names will have to be named something meaningful to the class/application itself.
Is the number 5 is in your question? If not get the number as input argument with the string input.

is This Data Abstration Example right or not?

i had given the following code in an interview. I want to know whether it is right or not..
public class DataAbstraction
{
public static void main (String args[])
{
MyDetails obj = new MyDetails();
obj.setNumebr(10);
obj.incrementBy(20);
int num = obj.getMumber();
System.out.println(num);
}
}
class MyDetails
{
private int n;
public void setNumebr(int i)
{
n = i;
}
public void incrementBy(int i)
{
n = n + i;
}
public int getMumber()
{
return n;
}
}
So please check it and correct me if i was wrong
There are many forms of abstractions in software. I would say that this is an example of data abstraction (though I would usually call it encapsulation). You could, if you would like to, change the member variable n to be of type... String(!), without changing the public interface of MyDetails.
Put differently: The details in the MyDetails class are hidden from the client code. The fact that MyDetails stores an int is abstracted away and it could be changed, for instance like this:
class MyDetails
{
private String n; // changed internal detail
public void setNumebr(int i)
{
n = "" + i;
}
public void incrementBy(int i)
{
n = "" + getMumber() + i;
}
public int getMumber()
{
return Integer.parseInt(n);
}
}
Have a look at the Wikipedia article on data abstraction for further details:
Abstraction > Data abstraction
Since there aren't enough details in the question its guessing time again:
1) No, its wrong. it contains various spelling errors like "getMumber" and "setNumebr".
2) Yes, if we ignore the spelling errors the methods seem to do what one would expect from their names.
2) No, it doesn't launch the rocket and it doesn't scale to multi processor machines (assuming these where the requirements).

Categories