Menu
Question Index
...

What is the output of the following program?

import java.lang.reflect.*;

public class Reflect {
    public static void main(String[] args) {
        Class noparams[] = {};
        Class[] paramString = new Class[1];
        paramString[0] = String.class;
        Class[] paramInt = new Class[1];
        paramInt[0] = Integer.TYPE;
        try {
            Class cls = Class.forName("AppTest");
            Object obj = cls.newInstance();
            Method method = cls.getDeclaredMethod("printIt", noparams);
            method.invoke(obj, null);
            method = cls.getDeclaredMethod("printIt", paramString);
            method.invoke(obj, new String("Merit Campus"));
            method = cls.getDeclaredMethod("setCounter", paramInt);
            method.invoke(obj, 999);
            System.out.println(cls.getDeclaredField(cls.getDeclaredFields()[0].getName()).getInt(obj));// LINE A
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
class AppTest {
    static int counter1;
    public void printIt() {
        System.out.println("No Params");
    }
    public void printIt(String temp) {
        System.out.println("String Param: " + temp);
    }
    protected void setCounter(int counter) { // BLOCK A
        System.out.println("setCounter: " + counter);
        counter1 = counter++;
    }
}


No Params
String Param: Merit Campus
setCounter: 999
1000
No Params
String Param: Merit Campus
setCounter: 999
999
Compilation Error at LINE A
Compilation Error in BLOCK A, because static variables can be initialized only in static block.
Runtime Error

Doubts

Problems

Topic: Advanced Java Programming Concepts

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App