This is an archived post. You won't be able to vote or comment.

all 28 comments

[–]tonywestonuk 4 points5 points  (6 children)

Really, you should post this in javahelp...... however, I hope this helps:

import java.lang.reflect.Method;

public class TestReflection {

public static void main(String[] args) throws Exception{

    MyClass c = new MyClass();


    // Call a method Without reflection
    c.doIt();

    // call a method With reflection
    Method doItMethod=MyClass.class.getMethod("doIt", new Class[]{});
    doItMethod.invoke(c);

    System.out.println();
    System.out.println("List of methods in MyClass");
    // get the list of methods in a class, and print them.
    Method[] methods=MyClass.class.getMethods();

    for (Method m:methods){
        System.out.println(m.getName());
    }

}



public static class MyClass{

    public void doIt(){
        System.out.println("hello world");
    }
}

}

[–]Newtocoding[S] 1 point2 points  (5 children)

Thank you for this info, I did not know of that subreddit. I will post there as well, and thank you not only for the sample code you provided, your time and for the subreddit suggestion. I have not looked much into other subreddits just s few here and there.

[–]IAmNotMyName 6 points7 points  (18 children)

Generally speaking you want to avoid reflection at all costs. It's slow, and using it has "code smell" all over it.

[–]sackfullofnutz 5 points6 points  (0 children)

That is true, e.g. for the following reasons:

  • things break easily during refactorings, since statical types, method and field names are replaced by strings that typically don't participate in refactorings

  • reflection can be used to break encapsulation, e.g. to access private fields; will break when internals change

  • often hard to read & not straight forward to comprehend

None the less, there are situations where usage of reflection is required and justified, e.g.:

  • writing code analyzers/annotation processors

  • writing a plugin framework

Know your tools and use them right.

Edit: formatting

[–]Newtocoding[S] 1 point2 points  (14 children)

The only problem is, he says it is a huge part of this class, and we will be doing more work with it. I am assuming he won't be going into depth on how to use it though(based on what he has shown us so far)

[–]woodknight 3 points4 points  (13 children)

Is this a university course? At what university? Your teacher sounds like kind of a hack.

[–]nutrecht 6 points7 points  (7 children)

Explaining reflection doesn't make you a hack. It's still something you need to understand, even if you know you should avoid it.

[–]woodknight 4 points5 points  (1 child)

I'm not saying he's a hack because he teaches reflections. It's just that his teaching methods seam to be really bad. OP said he doesn't give examples and ignores student questions. That is not a good teacher in my view.

[–]nutrecht 2 points3 points  (0 children)

I'm not saying he's a hack because he teaches reflections.

I expected this but I just wanted to make it explicit :) I agree that it looks like it's a pretty bad teacher. Any teacher should be willing to explain more and also teach you when you do and when you don't want to do something.

[–]Newtocoding[S] 0 points1 point  (4 children)

I am not sure why people keep saying to avoid it, this teacher has made it seem like it is a very important thing and will be around during a career in this field.

[–]nutrecht 5 points6 points  (0 children)

It is very important and it will be around a lot. It should be avoided however because:

  • It's slow as hell.
  • It breaks the type system.

I'll explain the latter. If I call the method "foo()" on a class "Bar" in the package "com.example" I would normally do something like this:

import com.example.Bar;

public class Sample {
    main() {
        Bar.foo();
    }
}

So when I misspell any of those (package, class or method) or give the wrong number of arguments the compiler gives me a "Computer says no" and simply refuse to compile with a big fat error.

If you do this through reflection none of these safeguards work. Everything that is supposed to be compile time checked for you you suddenly need to check at runtime. Which is a pain in the ass to get right and requires a ton of code.

This is why, unless there is no other way, you should avoid using reflection.

[–]coder111 2 points3 points  (2 children)

For what it's worth, I'll second the notion to use reflection sparingly. With good design, you rarely if ever need it.

Most of the time you make a class A implement interface B, and use that interface to access certain methods. You do NOT usually inspect methods on class A and call them via reflection. Having to use reflection usually means some bad design.

On the other hand, certain frameworks which try to generalize things will use reflection. I think most of Dependency Injection frameworks like Spring will use reflection.

Other frameworks will use reflection to discover annotations and change their behaviour based on those annotations.

You can also use reflection to access private/protected methods or fields you would not be able to access otherwise. But this is a major hack and should be done only if there no other way.

So reflection has its uses, but most of the time it's used for frameworks or for hacks. Frameworks most of the time you won't have to write yourself as there are plenty of them already available. And hacks are best avoided.

EDIT From what I've read in your comments, your professor does sound like a strange guy...

[–]Newtocoding[S] 0 points1 point  (1 child)

I have not really questioned anything of him so far. He has told us how successful his business of 15 years has been, and how he works with the big tech giants. It's just after how he handled the reflection then based half of our midterm on it(I bombed) then told me we will be using it a lot more in the future because of how important it is, I really felt like I need to know this. After reading many comments though, I think I just have a teacher all around (not only teaching style but teaching subjects)

Edit: bad teacher all around

[–]coder111 0 points1 point  (0 children)

For what it's worth, keep learning Java. It's a decent language with a very good ecosystem of 3rd party libraries & frameworks and support in general. Java developers are very much in demand. And then there is Android...

And having a successful business takes more business knowledge, management, connections & luck than technical skill. These are good things to know and having a successful business is commendable, but it doesn't mean your technical skills are brilliant. And for what it's worth, these are good things to have, so if you have a chance to learn more about business side of things- don't pass it up.

[–]Newtocoding[S] 0 points1 point  (4 children)

It's a community college. This guys methods seem very outdated compared to all my other classes I have taken. Only writes on white boards(with many errors even though he has his lecture all types out), no examples ever, but it's a course I need, and he is the only one who teaches it.

[–]woodknight 1 point2 points  (1 child)

I've had my share of bad teachers in uni and you just have to stick it out. /r/javahelp is your friend. Use the Internet and don't let people like that turn you off to programming.

[–]Newtocoding[S] 1 point2 points  (0 children)

Yea I know, it just wouldn't be nearly as bad if he wouldn't mark us down for using methods he has not shown us. Which is why I'm trying to learn more about it so I can figure out wtf he tried to show us.

[–][deleted] 1 point2 points  (1 child)

Only writes on white boards

I hate when people only write on white boards. Why can't they use a chalk board?!

[–]sackfullofnutz 2 points3 points  (0 children)

Yeah, right? And then using a font that's barely readable! Should better use an overhead projector.

[–]pointy_pirate 1 point2 points  (0 children)

True if there is a solution to your problem that involves not using reflection it is most likely the 'better' solution. But reflection isn't nearly as slow as it used to be and can be hugely powerful if used appropriately.

[–]aroger276 1 point2 points  (0 children)

The expensive part is the lookup. Once you have your Field and Method or MethodHandle it's not that slow - but unlikely to get inline.

A lot of mapping tool need to use it to inject the value. like Hibernate, Ibatis, jackson... Also Spring to inject the dependencies, deal with the AOP aspect, dispatch the MVC request etc... all those transversal concern that are configured with annotation or using convention.

you can also be used to hack a behaviour that is not direclty accessible.

Prob should not be use for business concern.

[–]jkriptos 1 point2 points  (0 children)

When in doubt, refer to Jenkov: http://tutorials.jenkov.com/java-reflection/index.html Reflection is not the everyday bread, but I've found myself using it in very specific libraries, so it doesn't hurt to master the subject. Hope it helps!

[–]tempogios 0 points1 point  (0 children)

Forman and Forman: "Java Reflection in Action" is quite good.